diff --git a/C/adtdefs.c b/C/adtdefs.c index e79ffb87a..b5aff1ed3 100755 --- a/C/adtdefs.c +++ b/C/adtdefs.c @@ -147,6 +147,32 @@ static inline Atom SearchAtom(const unsigned char *p, Atom a) { return (NIL); } +Atom +Yap_AtomInUse(const char *atom) { /* lookup atom in atom table */ + uint64_t hash; + const unsigned char *p; + Atom a, na = NIL; + AtomEntry *ae; + size_t sz = AtomHashTableSize; + + /* compute hash */ + p =( const unsigned char *) atom; + + hash = HashFunction(p); + hash = hash % sz; + /* we'll start by holding a read lock in order to avoid contention */ + READ_LOCK(HashChain[hash].AERWLock); + a = HashChain[hash].Entry; + /* search atom in chain */ + na = SearchAtom(p, a); + ae = RepAtom(na); + if (na != NIL ) { + READ_UNLOCK(HashChain[hash].AERWLock); + return (na); + } + READ_UNLOCK(HashChain[hash].AERWLock); + return NIL; +} static Atom LookupAtom(const unsigned char *atom) { /* lookup atom in atom table */ @@ -221,7 +247,7 @@ Atom Yap_LookupAtomWithLength(const char *atom, ptr = Yap_AllocCodeSpace(len0 + 1); if (!ptr) return NIL; - memcpy(ptr, atom, len0); + memmove(ptr, atom, len0); ptr[len0] = '\0'; at = LookupAtom(ptr); Yap_FreeCodeSpace(ptr); @@ -1010,7 +1036,7 @@ Atom Yap_LookupAtomWithLength(const char *atom, if (IsApplTerm(t0)) { Yap_FreeCodeSpace((char *)RepAppl(t0)); } - memcpy((void *)pt, (void *)ap, sz); + memmove((void *)pt, (void *)ap, sz); p->ValueOfVE = AbsAppl(pt); #endif } else if (IsStringTerm(v)) { @@ -1025,7 +1051,7 @@ Atom Yap_LookupAtomWithLength(const char *atom, if (IsApplTerm(t0)) { Yap_FreeCodeSpace((char *)RepAppl(t0)); } - memcpy((void *)pt, (void *)ap, sz); + memmove((void *)pt, (void *)ap, sz); p->ValueOfVE = AbsAppl(pt); } else { if (IsApplTerm(t0)) { diff --git a/C/adtdefs.c.new b/C/adtdefs.c.new index fed2fd720..02c395d45 100755 --- a/C/adtdefs.c.new +++ b/C/adtdefs.c.new @@ -216,7 +216,7 @@ Atom Yap_LookupAtomWithLength(const char *atom, ptr = Yap_AllocCodeSpace(len0 + 1); if (!ptr) return NIL; - memcpy(ptr, atom, len0); + memmove(ptr, atom, len0); ptr[len0] = '\0'; at = LookupAtom(ptr); Yap_FreeCodeSpace(ptr); @@ -1004,7 +1004,7 @@ void Yap_PutValue(Atom a, Term v) { if (IsApplTerm(t0)) { Yap_FreeCodeSpace((char *)RepAppl(t0)); } - memcpy((void *)pt, (void *)ap, sz); + memmove((void *)pt, (void *)ap, sz); p->ValueOfVE = AbsAppl(pt); #endif } else if (IsStringTerm(v)) { @@ -1019,7 +1019,7 @@ void Yap_PutValue(Atom a, Term v) { if (IsApplTerm(t0)) { Yap_FreeCodeSpace((char *)RepAppl(t0)); } - memcpy((void *)pt, (void *)ap, sz); + memmove((void *)pt, (void *)ap, sz); p->ValueOfVE = AbsAppl(pt); } else { if (IsApplTerm(t0)) { diff --git a/C/alloc.c b/C/alloc.c index e05341af7..165b32ad3 100644 --- a/C/alloc.c +++ b/C/alloc.c @@ -1329,7 +1329,7 @@ XX realloc(MALLOC_T ptr, size_t size) { MALLOC_T new = malloc(size); if (ptr) - memcpy(new, ptr, size); + memmove(new, ptr, size); free(ptr); return (new); } diff --git a/C/atomic.c b/C/atomic.c index 2294c8384..a23ac1b57 100755 --- a/C/atomic.c +++ b/C/atomic.c @@ -588,13 +588,25 @@ restart_aux: } } +/** @pred atom_codes(?A, ?L) is iso + + + The predicate holds when at least one of the arguments is + ground (otherwise, YAP will generate an error event. _A_ must be unifiable + with an atom, and the argument _L_ with the list of the character codes for + string _A_. + + +*/ static Int atom_codes(USES_REGS1) { Term t1; - t1 = Deref(ARG1); + LOCAL_MAX_SIZE = 1024; int l = push_text_stack(); + restart_aux: + t1 = Deref(ARG1); if (IsAtomTerm(t1)) { - Term tf = Yap_AtomToListOfCodes(t1 PASS_REGS); + Term tf = Yap_AtomSWIToListOfCodes(t1 PASS_REGS); if (tf) { pop_text_stack(l); return Yap_unify(ARG2, tf); @@ -602,17 +614,16 @@ restart_aux: } else if (IsVarTerm(t1)) { /* ARG1 unbound */ Term t = Deref(ARG2); - Atom af = Yap_ListToAtom(t PASS_REGS); + Atom af = Yap_ListOfCodesToAtom(t PASS_REGS); if (af) { pop_text_stack(l); return Yap_unify(ARG1, MkAtomTerm(af)); } - } else if (IsVarTerm(t1)) { - LOCAL_Error_TYPE = TYPE_ERROR_ATOM; + /* error handling */ + } else { + Yap_ThrowError(TYPE_ERROR_ATOM, t1, NULL); } - /* error handling */ if (LOCAL_Error_TYPE && Yap_HandleError("atom_codes/2")) { - t1 = Deref(ARG1); goto restart_aux; } { @@ -717,14 +728,14 @@ static Int number_chars(USES_REGS1) { pop_text_stack(l); return Yap_unify(ARG1, tf); } - pop_text_stack(l); + pop_text_stack(l); LOCAL_ActiveError->errorRawTerm = 0; Yap_ThrowExistingError(); return false; } - pop_text_stack(l); + pop_text_stack(l); return true; } @@ -1367,7 +1378,7 @@ restart_aux: LOCAL_Error_TYPE = TYPE_ERROR_LIST; } else { seq_tv_t *inpv = (seq_tv_t *)Malloc(n * sizeof(seq_tv_t)); - seq_tv_t *out = (seq_tv_t *)Malloc( sizeof(seq_tv_t)); + seq_tv_t *out = (seq_tv_t *)Malloc(sizeof(seq_tv_t)); int i = 0; if (!inpv) { LOCAL_Error_TYPE = RESOURCE_ERROR_HEAP; @@ -1455,9 +1466,7 @@ error: if (LOCAL_Error_TYPE && Yap_HandleError("atom_concat/3")) { goto restart_aux; } - { - return FALSE; - } + { return FALSE; } } static Int atomics_to_string2(USES_REGS1) { @@ -2070,7 +2079,7 @@ static Int atom_split(USES_REGS1) { } size_t b_mid = skip_utf8(s0, u_mid) - s0; s1 = s10 = Malloc(b_mid + 1); - memcpy(s1, s, b_mid); + memmove(s1, s, b_mid); s1[b_mid] = '\0'; to1 = MkAtomTerm(Yap_ULookupAtom(s10)); to2 = MkAtomTerm(Yap_ULookupAtom(s0 + b_mid)); @@ -2756,6 +2765,8 @@ void Yap_InitAtomPreds(void) { Yap_InitCPred("downcase_atom", 2, downcase_text_to_atom, 0); Yap_InitCPred("upcase_text_to_atom", 2, upcase_text_to_atom, 0); Yap_InitCPred("upcase_atom", 2, upcase_text_to_atom, 0); + Yap_InitCPred("text_to_string", 2, downcase_text_to_string, 0); + Yap_InitCPred("text_to_atom", 2, downcase_text_to_string, 0); Yap_InitCPred("downcase_text_to_string", 2, downcase_text_to_string, 0); Yap_InitCPred("upcase_text_to_string", 2, upcase_text_to_string, 0); Yap_InitCPred("downcase_text_to_codes", 2, downcase_text_to_codes, 0); diff --git a/C/blobs.c b/C/blobs.c index be3eb8486..69bcb642c 100644 --- a/C/blobs.c +++ b/C/blobs.c @@ -48,7 +48,7 @@ char *Yap_blob_to_string(AtomEntry *ref, const char *s0, size_t sz) { size_t sz0 = strlcpy(s, (char *)RepAtom(AtomSWIStream)->StrOfAE, sz); #else size_t sz0; - char *f = (char *)memcpy(s, (char *)RepAtom(AtomSWIStream)->StrOfAE, sz); + char *f = (char *)memmove(s, (char *)RepAtom(AtomSWIStream)->StrOfAE, sz); f[0] = '\0'; sz0 = f - s; #endif @@ -156,7 +156,7 @@ AtomEntry *Yap_lookupBlob(void *blob, size_t len, void *type0, int *new) { ae->PropsOfAE = AbsBlobProp(b); ae->NextOfAE = AbsAtom(Blobs); ae->rep.blob->length = len; - memcpy(ae->rep.blob->data, blob, len); + memmove(ae->rep.blob->data, blob, len); Blobs = ae; if (NOfBlobs > NOfBlobsMax) { Yap_signal(YAP_CDOVF_SIGNAL); diff --git a/C/c_interface.c b/C/c_interface.c index 6277a5f35..1a30a292a 100755 --- a/C/c_interface.c +++ b/C/c_interface.c @@ -288,13 +288,23 @@ X_API Term YAP_MkIntTerm(Int n) { } X_API Term YAP_MkStringTerm(const char *n) { - CACHE_REGS - Term I; - BACKUP_H(); + CACHE_REGS + Term I; + BACKUP_H(); - I = MkStringTerm(n); - RECOVER_H(); - return I; + I = MkStringTerm(n); + RECOVER_H(); + return I; +} + +X_API Term YAP_MkCharPTerm( char *n) { + CACHE_REGS + Term I; + BACKUP_H(); + + I = MkStringTerm(n); + RECOVER_H(); + return I; } X_API Term YAP_MkUnsignedStringTerm(const unsigned char *n) { @@ -1898,7 +1908,7 @@ X_API YAP_opaque_tag_t YAP_NewOpaqueType(struct YAP_opaque_handler_struct *f) { return -1; } i = GLOBAL_OpaqueHandlersCount++; - memcpy(GLOBAL_OpaqueHandlers + i, f, sizeof(YAP_opaque_handler_t)); + memmove(GLOBAL_OpaqueHandlers + i, f, sizeof(YAP_opaque_handler_t)); return i; } @@ -2129,20 +2139,16 @@ X_API int YAP_InitConsult(int mode, const char *fname, char **full, int *osnop) char *d = Malloc(strlen(fl)+1); strcpy(d,fl); bool consulted = (mode == YAP_CONSULT_MODE); - sno = Yap_OpenStream(MkStringTerm(fl), "r", MkAtomTerm(Yap_LookupAtom(fl)), LOCAL_encoding); + Term tat = MkAtomTerm(Yap_LookupAtom(d)); + sno = Yap_OpenStream(tat, "r", MkAtomTerm(Yap_LookupAtom(fname)), LOCAL_encoding); if (sno < 0 || !Yap_ChDir(dirname((char *)d))) { pop_text_stack(lvl); *full = NULL; return -1; - } - LOCAL_PrologMode = UserMode; + } LOCAL_PrologMode = UserMode; - Yap_init_consult(consulted, fl); - GLOBAL_Stream[sno].name = Yap_LookupAtom(fl); - GLOBAL_Stream[sno].user_name = MkAtomTerm(Yap_LookupAtom(fname)); - GLOBAL_Stream[sno].encoding = LOCAL_encoding; - *full = pop_output_text_stack(lvl, fl); + Yap_init_consult(consulted, pop_output_text_stack__(lvl,fl)); RECOVER_MACHINE_REGS(); UNLOCK(GLOBAL_Stream[sno].streamlock); return sno; @@ -2176,7 +2182,8 @@ X_API void YAP_EndConsult(int sno, int *osnop, const char *full) { if (osnop >= 0) Yap_AddAlias(AtomLoopStream, *osnop); Yap_end_consult(); - __android_log_print(ANDROID_LOG_INFO, "YAPDroid ", " closing %s(%d), %d", full, *osnop, sno); + __android_log_print(ANDROID_LOG_INFO, "YAPDroid ", " closing %s:%s(%d), %d", + CurrentModule == 0? "prolog": RepAtom(AtomOfTerm(CurrentModule))->StrOfAE, full, *osnop, sno); // LOCAL_CurSlot); pop_text_stack(lvl); RECOVER_MACHINE_REGS(); @@ -2264,8 +2271,8 @@ X_API int YAP_WriteDynamicBuffer(YAP_Term t, char *buf, size_t sze, char *b; BACKUP_MACHINE_REGS(); - b = Yap_TermToBuffer(t, enc, flags); - strncpy(buf, b, sze); + b = Yap_TermToBuffer(t, flags); + strncpy(buf, b, sze-1); buf[sze] = 0; RECOVER_MACHINE_REGS(); return true; @@ -2364,7 +2371,7 @@ X_API void YAP_FlushAllStreams(void) { X_API void YAP_Throw(Term t) { BACKUP_MACHINE_REGS(); LOCAL_ActiveError->errorNo = THROW_EVENT; - LOCAL_ActiveError->errorGoal = Yap_TermToBuffer(t, LOCAL_encoding, 0); + LOCAL_ActiveError->errorGoal = Yap_TermToBuffer(t, 0); Yap_JumpToEnv(); RECOVER_MACHINE_REGS(); } @@ -2374,7 +2381,7 @@ X_API void YAP_AsyncThrow(Term t) { BACKUP_MACHINE_REGS(); LOCAL_PrologMode |= AsyncIntMode; LOCAL_ActiveError->errorNo = THROW_EVENT; - LOCAL_ActiveError->errorGoal = Yap_TermToBuffer(t, LOCAL_encoding, 0); + LOCAL_ActiveError->errorGoal = Yap_TermToBuffer(t, 0); Yap_JumpToEnv(); LOCAL_PrologMode &= ~AsyncIntMode; RECOVER_MACHINE_REGS(); @@ -3104,7 +3111,7 @@ X_API Int YAP_AtomToInt(YAP_Atom At) { "No more room for translations"); return -1; } - memcpy(nt, ot, sizeof(atom_t) * MaxAtomTranslations); + memmove(nt, ot, sizeof(atom_t) * MaxAtomTranslations); TR_Atoms = nt; free(ot); MaxAtomTranslations *= 2; @@ -3132,7 +3139,7 @@ X_API Int YAP_FunctorToInt(YAP_Functor f) { "No more room for translations"); return -1; } - memcpy(nt, ot, sizeof(functor_t) * MaxFunctorTranslations); + memmove(nt, ot, sizeof(functor_t) * MaxFunctorTranslations); TR_Functors = nt; free(ot); MaxFunctorTranslations *= 2; diff --git a/C/cdmgr.c b/C/cdmgr.c index 013ea7df1..3ffb16e7d 100644 --- a/C/cdmgr.c +++ b/C/cdmgr.c @@ -301,7 +301,7 @@ void Yap_BuildMegaClause(PredEntry *ap) { mcl->ClLine = cl->usc.ClLine; ptr = mcl->ClCode; while (TRUE) { - memcpy((void *)ptr, (void *)cl->ClCode, sz); + memmove((void *)ptr, (void *)cl->ClCode, sz); if (has_blobs) { LOCAL_ClDiff = (char *)(ptr) - (char *)cl->ClCode; restore_opcodes(ptr, NULL PASS_REGS); @@ -380,7 +380,7 @@ static void split_megaclause(PredEntry *ap) { new->ClSize = mcl->ClItemSize; new->usc.ClLine = Yap_source_line_no(); new->ClNext = NULL; - memcpy((void *)new->ClCode, (void *)ptr, mcl->ClItemSize); + memmove((void *)new->ClCode, (void *)ptr, mcl->ClItemSize); if (prev) { prev->ClNext = new; } else { @@ -1386,7 +1386,7 @@ static void expand_consult(void) { } new_cs = new_cl + InitialConsultCapacity; /* start copying */ - memcpy((void *)new_cs, (void *)LOCAL_ConsultLow, + memmove((void *)new_cs, (void *)LOCAL_ConsultLow, OldConsultCapacity * sizeof(consult_obj)); /* copying done, release old space */ Yap_FreeCodeSpace((char *)LOCAL_ConsultLow); @@ -1768,6 +1768,7 @@ bool Yap_addclause(Term t, yamop *cp, Term tmode, Term mod, Term *t4ref) disc[2] = Yap_Module_Name(p); sc[0] = Yap_MkApplTerm(Yap_MkFunctor(AtomDiscontiguous, 3), 3, disc); sc[1] = MkIntegerTerm(Yap_source_line_no()); + __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "source %s ", RepAtom(LOCAL_SourceFileName)->StrOfAE); sc[2] = MkAtomTerm(LOCAL_SourceFileName); sc[3] = t; t = Yap_MkApplTerm(Yap_MkFunctor(AtomStyleCheck, 4), 4, sc); @@ -2064,7 +2065,7 @@ Atom Yap_ConsultingFile(USES_REGS1) { if (LOCAL_consult_level == 0) { return (AtomUser); } else { - return (Yap_ULookupAtom(LOCAL_ConsultBase[2].f_name)); + return LOCAL_ConsultBase[2].f_name; } } @@ -2078,7 +2079,7 @@ void Yap_init_consult(int mode, const char *filenam) { expand_consult(); } LOCAL_ConsultSp--; - LOCAL_ConsultSp->f_name = (const unsigned char *)filenam; + LOCAL_ConsultSp->f_name = Yap_LookupAtom(filenam); LOCAL_ConsultSp--; LOCAL_ConsultSp->mode = mode; LOCAL_ConsultSp--; diff --git a/C/compiler.c b/C/compiler.c index cb307bb43..dc301c997 100644 --- a/C/compiler.c +++ b/C/compiler.c @@ -719,7 +719,7 @@ restart: dest = Yap_emit_extra_size(blob_op, sz / CellSize, sz, &cglobs->cint); /* copy the bignum */ - memcpy(dest, src, sz); + memmove(dest, src, sz); /* note that we don't need to copy size info, unless we wanted to garbage collect clauses ;-) */ cglobs->cint.icpc = cglobs->cint.cpc; @@ -758,7 +758,7 @@ restart: dest = Yap_emit_extra_size(blob_op, sz / CellSize, sz, &cglobs->cint); /* copy the bignum */ - memcpy(dest, src, sz); + memmove(dest, src, sz); /* note that we don't need to copy size info, unless we wanted to garbage collect clauses ;-) */ cglobs->cint.icpc = cglobs->cint.cpc; diff --git a/C/dbase.c b/C/dbase.c index 57e52a05f..05556ef76 100644 --- a/C/dbase.c +++ b/C/dbase.c @@ -642,7 +642,7 @@ static CELL *copy_double(CELL *st, CELL *pt) { static CELL *copy_string(CELL *st, CELL *pt) { UInt sz = pt[1] + 3; /* first thing, store a link to the list before we move on */ - memcpy(st, pt, sizeof(CELL) * sz); + memmove(st, pt, sizeof(CELL) * sz); /* now reserve space */ return st + sz; } @@ -656,7 +656,7 @@ static CELL *copy_big_int(CELL *st, CELL *pt) { st[0] = (CELL)FunctorBigInt; st[1] = pt[1]; /* then the actual number */ - memcpy((void *)(st + 2), (void *)(pt + 2), sz); + memmove((void *)(st + 2), (void *)(pt + 2), sz); st = st + 2 + sz / CellSize; /* then the tail for gc */ st[0] = EndSpecials; @@ -968,7 +968,7 @@ loop: if (HR + sz >= ASP) { goto error2; } - memcpy((void *)HR, (void *)(to_visit_base), sz * sizeof(CELL *)); + memmove((void *)HR, (void *)(to_visit_base), sz * sizeof(CELL *)); to_visit_base = (CELL **)HR; to_visit = to_visit_base + sz; } @@ -1684,7 +1684,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat, nar = ppt->Contents + Unsigned(NOfCells); } woar = (link_entry *)nar; - memcpy((void *)woar, (const void *)dbg->LinkAr, + memmove((void *)woar, (const void *)dbg->LinkAr, (size_t)(NOfLinks * sizeof(link_entry))); woar += NOfLinks; #ifdef ALIGN_LONGS diff --git a/C/dlmalloc.c b/C/dlmalloc.c index e7ddcb1dd..d522ac825 100644 --- a/C/dlmalloc.c +++ b/C/dlmalloc.c @@ -1978,7 +1978,7 @@ Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes; assert(ncopies >= 3); if (ncopies > 9) - memcpy(d, s, copysize); + memmove(d, s, copysize); else { *(d+0) = *(s+0); @@ -2077,7 +2077,7 @@ Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes; /* Must alloc, copy, free. */ newmem = mALLOc(nb - MALLOC_ALIGN_MASK); if (newmem != 0) { - memcpy(newmem, oldmem, oldsize - 2*SIZE_SZ); + memmove(newmem, oldmem, oldsize - 2*SIZE_SZ); fREe(oldmem); } } diff --git a/C/errors.c b/C/errors.c index 7d9bebe72..daf573a35 100755 --- a/C/errors.c +++ b/C/errors.c @@ -49,7 +49,7 @@ const char *s = IsAtomTerm(t) ? RepAtom(AtomOfTerm(t))->StrOfAE \ : IsStringTerm(t) ? StringOfTerm(t) : NULL; \ if (s) { \ - char *tmp = malloc(strlen(s) + 1); \ + char *tmp = calloc(1,strlen(s) + 1); \ strcpy(tmp, s); \ i->k = tmp; \ } \ @@ -90,21 +90,23 @@ static bool setErr(const char *q, yap_error_descriptor_t *i, Term t) { return i->k ? TermTrue : TermFalse; \ } -#define query_key_i(k, ks, q, i) \ - if (strcmp(ks, q) == 0) { \ +#define query_key_i(k, ks, q, i) if (strcmp(ks, q) == 0) { \ return MkIntegerTerm(i->k); \ } -#define query_key_s(k, ks, q, i) \ +#define query_key_s(k, ks, q, i) \ + if (strcmp(ks, q) == 0 && i->k) { \ + return MkAtomTerm(Yap_LookupAtom(i->k)); } else {return TermNil;} + +#define query_key_t(k, ks, q, i) \ if (strcmp(ks, q) == 0) { \ - return (i->k && i->k[0] ? MkStringTerm(i->k) : TermNil); \ - } + Term t; if((t = Yap_BufferToTerm(i->k, TermNil) ) == 0 ) return TermNil; return t; } static Term queryErr(const char *q, yap_error_descriptor_t *i) { query_key_i(errorNo, "errorNo", q, i); query_key_i(errorClass, "errorClass", q, i); query_key_s(errorAsText, "errorAsText", q, i); - query_key_s(errorGoal, "errorGoal", q, i); + query_key_t(errorGoal, "errorGoal", q, i); query_key_s(classAsText, "classAsText", q, i); query_key_i(errorLine, "errorLine", q, i); query_key_s(errorFunction, "errorFunction", q, i); @@ -123,7 +125,7 @@ static Term queryErr(const char *q, yap_error_descriptor_t *i) { query_key_s(prologParserText, "prologParserText", q, i); query_key_s(prologParserFile, "prologParserFile", q, i); query_key_b(prologConsulting, "prologConsulting", q, i); - query_key_s(culprit, "culprit", q, i); + query_key_t(culprit, "culprit", q, i); query_key_s(errorMsg, "errorMsg", q, i); query_key_i(errorMsgLen, "errorMsgLen", q, i); return TermNil; @@ -148,10 +150,10 @@ static void printErr(yap_error_descriptor_t *i) { return; } print_key_i("errorNo", i->errorNo); - print_key_i("errorClass", i->errorClass); - print_key_s("errorAsText", i->errorAsText); + print_key_i("errorClass", (i->errorClass = Yap_errorClass(i->errorNo))); + print_key_s("errorAsText", (i->errorAsText=Yap_errorName(i->errorNo) ) ); print_key_s("errorGoal", i->errorGoal); - print_key_s("classAsText", i->classAsText); + print_key_s("classAsText", (i->classAsText=Yap_errorClassName(i->errorClass))); print_key_i("errorLine", i->errorLine); print_key_s("errorFunction", i->errorFunction); print_key_s("errorFile", i->errorFile); @@ -322,7 +324,7 @@ bool Yap_PrintWarning(Term twarning) { PredEntry *pred = RepPredProp(PredPropByFunc( FunctorPrintMessage, PROLOG_MODULE)); // PROCEDURE_print_message2; __android_log_print(ANDROID_LOG_INFO, "YAPDroid ", " warning(%s)", - Yap_TermToBuffer(twarning, ENC_ISO_UTF8,Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f)); + Yap_TermToBuffer(twarning, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f)); Term cmod = (CurrentModule == PROLOG_MODULE ? TermProlog : CurrentModule); bool rc; Term ts[2], err; @@ -330,7 +332,7 @@ bool Yap_PrintWarning(Term twarning) { if (LOCAL_PrologMode & InErrorMode && LOCAL_ActiveError && (err = LOCAL_ActiveError->errorNo)) { fprintf(stderr, "%% Warning %s while processing error: %s %s\n", - Yap_TermToBuffer(twarning, ENC_ISO_UTF8, + Yap_TermToBuffer(twarning, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f), Yap_errorClassName(Yap_errorClass(err)), Yap_errorName(err)); return false; @@ -581,23 +583,17 @@ bool Yap_pushErrorContext(bool pass, yap_error_descriptor_t *new_error) { /* if (Yap_HasException()) */ /* memset(LOCAL_ActiveError, 0, sizeof(*LOCAL_ActiveError)); */ /* LOCAL_ActiveError->top_error = bf; */ - /* } */ yap_error_descriptor_t *Yap_popErrorContext(bool mdnew, bool pass) { - yap_error_descriptor_t *e = LOCAL_ActiveError; + yap_error_descriptor_t *e = LOCAL_ActiveError, *ep = LOCAL_ActiveError->top_error; // last block - LOCAL_ActiveError = e->top_error; - if (e->errorNo) { - if (!LOCAL_ActiveError->errorNo && pass) { - memcpy(LOCAL_ActiveError, e, sizeof(*LOCAL_ActiveError)); - } else { - return e; - } - } else { - if (e->errorNo) - return e; + LOCAL_ActiveError = ep; + if (e->errorNo && !ep->errorNo && pass) { + yap_error_descriptor_t *epp = ep->top_error; + memmove(ep, e, sizeof(*e)); + ep->top_error = epp; } - return NULL; + return LOCAL_ActiveError; } /** * Throw an error directly to the error handler @@ -652,7 +648,7 @@ bool Yap_MkErrorRecord(yap_error_descriptor_t *r, const char *file, r->culprit = NULL; } else { r->culprit = Yap_TermToBuffer( - where, ENC_ISO_UTF8, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f); + where, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f); } if (LOCAL_consult_level > 0) { r->prologParserFile = Yap_ConsultingFile(PASS_REGS1)->StrOfAE; @@ -941,6 +937,7 @@ typedef struct c_error_info { ; #include +#include yap_error_class_number Yap_errorClass(yap_error_number e) { return c_error_list[e].class; @@ -956,8 +953,8 @@ yap_error_descriptor_t *Yap_GetException(yap_error_descriptor_t *i) { CACHE_REGS if (i->errorNo != YAP_NO_ERROR) { yap_error_descriptor_t *t = LOCAL_ActiveError, - *nt = malloc(sizeof(yap_error_descriptor_t)); - memcpy(nt, t, sizeof(yap_error_descriptor_t)); + *nt = calloc(1,sizeof(yap_error_descriptor_t)); + memmove(nt, t, sizeof(yap_error_descriptor_t)); return nt; } return 0; @@ -989,8 +986,11 @@ static Int reset_exception(USES_REGS1) { return Yap_ResetException(worker_id); } Term MkErrorTerm(yap_error_descriptor_t *t) { if (t->errorClass == EVENT) return t->errorRawTerm; + Term tc = t->culprit ? Yap_BufferToTerm(t->culprit, TermNil) : TermNil; + if (tc == 0) + tc = MkAtomTerm(Yap_LookupAtom(t->culprit)); return mkerrort(t->errorNo, - t->culprit ? Yap_BufferToTerm(t->culprit, TermNil) : TermNil, + tc, err2list(t)); } @@ -1002,8 +1002,13 @@ static Int read_exception(USES_REGS1) { } static Int print_exception(USES_REGS1) { - yap_error_descriptor_t *t = AddressOfTerm(Deref(ARG1)); - printErr(t); + Term t1 = Deref(ARG1); + if (IsAddressTerm(t1)) { + yap_error_descriptor_t *t = AddressOfTerm(t1); + printErr(t); + } else { + return Yap_WriteTerm(LOCAL_c_error_stream,t1,TermNil PASS_REGS); + } // Yap_DebugPlWriteln(rc); return true; } @@ -1144,7 +1149,7 @@ yap_error_descriptor_t *Yap_UserError(Term t, yap_error_descriptor_t *i) { n = t2; } i->errorGoal = Yap_TermToBuffer( - n, ENC_ISO_UTF8, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f); + n, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f); } Yap_prolog_add_culprit(i PASS_REGS); return i; diff --git a/C/exec.c b/C/exec.c index 56987beb8..4386810c9 100755 --- a/C/exec.c +++ b/C/exec.c @@ -1460,7 +1460,7 @@ static bool exec_absmi(bool top, yap_reset_t reset_mode USES_REGS) { */ /* reset the registers so that we don't have trash in abstract * machine */ - pop_text_stack(i+1); + pop_text_stack(i + 1); Yap_set_fpu_exceptions( getAtomicGlobalPrologFlag(ARITHMETIC_EXCEPTIONS_FLAG)); P = (yamop *)FAILCODE; @@ -1470,12 +1470,12 @@ static bool exec_absmi(bool top, yap_reset_t reset_mode USES_REGS) { } break; case 3: { /* saved state */ // LOCAL_ActiveError = err_info; - pop_text_stack(i+1); + pop_text_stack(i + 1); LOCAL_CBorder = OldBorder; LOCAL_RestartEnv = sighold; LOCAL_PrologMode = UserMode; - LOCAL_DoingUndefp = false; -Yap_CloseSlots(sls); + LOCAL_DoingUndefp = false; + Yap_CloseSlots(sls); return false; } case 4: @@ -1485,16 +1485,16 @@ Yap_CloseSlots(sls); // LOCAL_ActiveError = err_info; while (B) { LOCAL_ActiveError->errorNo = ABORT_EVENT; - pop_text_stack(i+1); + pop_text_stack(i + 1); Yap_CloseSlots(sls); Yap_JumpToEnv(); } LOCAL_PrologMode = UserMode; - LOCAL_DoingUndefp = false; - P = (yamop *)FAILCODE; + LOCAL_DoingUndefp = false; + P = (yamop *)FAILCODE; LOCAL_RestartEnv = sighold; Yap_CloseSlots(sls); - pop_text_stack(i+1); + pop_text_stack(i + 1); return false; break; case 5: @@ -1517,15 +1517,15 @@ Yap_CloseSlots(sls); (CELL *)(B->cp_b) > LCL0 - LOCAL_CBorder) { LOCAL_RestartEnv = sighold; LOCAL_CBorder = OldBorder; - pop_text_stack(i+1); - return false; + pop_text_stack(i + 1); + return false; } P = FAILCODE; } } YENV = ASP; YENV[E_CB] = Unsigned(B); - pop_text_stack(i+1); + pop_text_stack(i + 1); out = Yap_absmi(0); /* make sure we don't leave a FAIL signal hanging around */ Yap_get_signal(YAP_FAIL_SIGNAL); @@ -1533,7 +1533,7 @@ Yap_CloseSlots(sls); CalculateStackGap(PASS_REGS1); LOCAL_CBorder = OldBorder; LOCAL_RestartEnv = sighold; - pop_text_stack(i+1); + pop_text_stack(i + 1); return out; } @@ -2116,7 +2116,8 @@ static Int jump_env(USES_REGS1) { } // Yap_DebugPlWriteln(t); // char *buf = Yap_TermToBuffer(t, ENC_ISO_UTF8, - // Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f); + // Quote_illegal_f | Ignore_ops_f | + // Unfold_cyclics_f); // __android_log_print(ANDROID_LOG_INFO, "YAPDroid ", " throw(%s)", buf); LOCAL_ActiveError = Yap_UserError(t0, LOCAL_ActiveError); bool out = JumpToEnv(PASS_REGS1); @@ -2124,7 +2125,7 @@ static Int jump_env(USES_REGS1) { LCL0 - (CELL *)B > LOCAL_CBorder) { // we're failing up to the top layer } - pop_text_stack(LOCAL_MallocDepth+1); + pop_text_stack(LOCAL_MallocDepth + 1); return out; } diff --git a/C/exo_udi.c b/C/exo_udi.c index 90a9cf382..0148cda40 100755 --- a/C/exo_udi.c +++ b/C/exo_udi.c @@ -253,7 +253,7 @@ IntervalUDIRefitIndex(struct index_t **ip, UInt b[] USES_REGS) qsort(s0+1, (size_t)*s0, sizeof(BITS32), compar); it->links[offset0] = s0-sorted0; if (it->udi_free_args) { - memcpy(sorted, s0+1, sizeof(BITS32)*(*s0)); + memmove(sorted, s0+1, sizeof(BITS32)*(*s0)); qsort(sorted, (size_t)*s0, sizeof(BITS32), compar2); sorted += *s0; } diff --git a/C/flags.c b/C/flags.c index c5ce98ce4..e762e41ce 100644 --- a/C/flags.c +++ b/C/flags.c @@ -1,19 +1,19 @@ /************************************************************************* -* * -* YAP Prolog * -* * -* Yap Prolog was developed at NCCUP - Universidade do Porto * -* * -* Copyright L.Damas, V.S.Costa and Universidade do Porto 2015- * -* * -************************************************************************** -* * -* File: flags.c * -* Last rev: * -* mods: * -* comments: abstract machine definitions * -* * -*************************************************************************/ + * * + * YAP Prolog * + * * + * Yap Prolog was developed at NCCUP - Universidade do Porto * + * * + * Copyright L.Damas, V.S.Costa and Universidade do Porto 2015- * + * * + ************************************************************************** + * * + * File: flags.c * + * Last rev: * + * mods: * + * comments: abstract machine definitions * + * * + *************************************************************************/ /** @file C/flags.c @@ -80,22 +80,29 @@ static void newFlag(Term fl, Term val); static Int current_prolog_flag(USES_REGS1); static Int set_prolog_flag(USES_REGS1); -#include "Yatom.h" #include "YapEval.h" +#include "Yatom.h" #include "yapio.h" -#define YAP_FLAG(ID, NAME, WRITABLE, DEF, INIT, HELPER) { NAME, WRITABLE, DEF, INIT, HELPER } +#define YAP_FLAG(ID, NAME, WRITABLE, DEF, INIT, HELPER) \ + { NAME, WRITABLE, DEF, INIT, HELPER } #define START_LOCAL_FLAGS static flag_info local_flags_setup[] = { -#define END_LOCAL_FLAGS LZERO_FLAG}; +#define END_LOCAL_FLAGS \ + LZERO_FLAG \ + } \ + ; #define START_GLOBAL_FLAGS static flag_info global_flags_setup[] = { -#define END_GLOBAL_FLAGS GZERO_FLAG}; - - -#define GZERO_FLAG { NULL, false, NULL, NULL, NULL } -#define LZERO_FLAG { NULL, false, NULL, NULL, NULL } +#define END_GLOBAL_FLAGS \ + GZERO_FLAG \ + } \ + ; +#define GZERO_FLAG \ + { NULL, false, NULL, NULL, NULL } +#define LZERO_FLAG \ + { NULL, false, NULL, NULL, NULL } #include "YapGFlagInfo.h" @@ -111,8 +118,7 @@ static Term indexer(Term inp) { "set_prolog_flag index in {off,single,compact,multi,on,max}"); return TermZERO; } - Yap_Error(TYPE_ERROR_ATOM, inp, - "set_prolog_flag in {dec10,error,fail,quiet}"); + Yap_Error(TYPE_ERROR_ATOM, inp, "set_prolog_flag index to an atom"); return TermZERO; } @@ -133,14 +139,16 @@ static bool dqf1(ModEntry *new, Term t2 USES_REGS) { return true; } /* bad argument, but still an atom */ - Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2, "bad option %s for backquoted " - "string flag, use one string, " - "atom, codes or chars", + Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2, + "bad option %s for backquoted " + "string flag, use one string, " + "atom, codes or chars", RepAtom(AtomOfTerm(t2))->StrOfAE); return false; } else { - Yap_Error(TYPE_ERROR_ATOM, t2, "set_prolog_flag(double_quotes, %s), should " - "be {string,atom,codes,chars}", + Yap_Error(TYPE_ERROR_ATOM, t2, + "set_prolog_flag(double_quotes, %s), should " + "be {string,atom,codes,chars}", RepAtom(AtomOfTerm(t2))->StrOfAE); return false; } @@ -168,9 +176,10 @@ static bool bqf1(ModEntry *new, Term t2 USES_REGS) { new->flags |= BCKQ_CHARS; return true; } - Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2, "bad option %s for backquoted " - "string flag, use one string, " - "atom, codes or chars", + Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2, + "bad option %s for backquoted " + "string flag, use one string, " + "atom, codes or chars", RepAtom(AtomOfTerm(t2))->StrOfAE); return false; } else { @@ -186,7 +195,6 @@ static bool bqs(Term t2) { return bqf1(new, t2 PASS_REGS); } - static bool sqf1(ModEntry *new, Term t2 USES_REGS) { new->flags &= ~(SNGQ_CHARS | SNGQ_CODES | SNGQ_ATOM | SNGQ_STRING); if (IsAtomTerm(t2)) { @@ -203,9 +211,10 @@ static bool sqf1(ModEntry *new, Term t2 USES_REGS) { new->flags |= SNGQ_CHARS; return true; } - Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2, "bad option %s for backquoted " - "string flag, use one string, " - "atom, codes or chars", + Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2, + "bad option %s for backquoted " + "string flag, use one string, " + "atom, codes or chars", RepAtom(AtomOfTerm(t2))->StrOfAE); return false; } else { @@ -215,7 +224,6 @@ static bool sqf1(ModEntry *new, Term t2 USES_REGS) { } } - static bool sqf(Term t2) { CACHE_REGS ModEntry *new = Yap_GetModuleEntry(CurrentModule); @@ -239,8 +247,9 @@ static Term isaccess(Term inp) { static Term stream(Term inp) { if (IsVarTerm(inp)) return inp; - if (Yap_CheckStream(inp, Input_Stream_f | Output_Stream_f | Append_Stream_f | - Socket_Stream_f, + if (Yap_CheckStream(inp, + Input_Stream_f | Output_Stream_f | Append_Stream_f | + Socket_Stream_f, "yap_flag/3") >= 0) return inp; return 0; @@ -249,19 +258,19 @@ static Term stream(Term inp) { static bool set_error_stream(Term inp) { if (IsVarTerm(inp)) return Yap_unify(inp, Yap_StreamUserName(LOCAL_c_error_stream)); - return Yap_SetErrorStream( inp ); + return Yap_SetErrorStream(inp); } static bool set_input_stream(Term inp) { if (IsVarTerm(inp)) return Yap_unify(inp, Yap_StreamUserName(LOCAL_c_input_stream)); - return Yap_SetInputStream( inp ); + return Yap_SetInputStream(inp); } static bool set_output_stream(Term inp) { if (IsVarTerm(inp)) return Yap_unify(inp, Yap_StreamUserName(LOCAL_c_output_stream)); - return Yap_SetOutputStream( inp ); + return Yap_SetOutputStream(inp); } static Term isground(Term inp) { @@ -468,7 +477,7 @@ static bool typein(Term inp) { return true; } - static bool list_atom( Term inp ) { +x static bool list_atom( Term inp ) { if (IsVarTerm(inp)) { Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag in \"...\""); return false; @@ -731,10 +740,10 @@ static bool setYapFlagInModule(Term tflag, Term t2, Term mod) { if (IsVarTerm(tout)) { Term t; while ((t = Yap_PopTermFromDB(tarr[fv->FlagOfVE].DBT)) == 0) { - if (!Yap_gc(2, ENV, gc_P(P, CP))) { - Yap_Error(RESOURCE_ERROR_STACK, TermNil, LOCAL_ErrorMessage); - return false; - } + if (!Yap_gc(2, ENV, gc_P(P, CP))) { + Yap_Error(RESOURCE_ERROR_STACK, TermNil, LOCAL_ErrorMessage); + return false; + } } } else if (IsAtomOrIntTerm(t2)) tarr[fv->FlagOfVE].at = t2; @@ -782,7 +791,6 @@ static bool setYapFlagInModule(Term tflag, Term t2, Term mod) { return bqf1(me, t2 PASS_REGS); } else if (fv->FlagOfVE == SINGLE_QUOTES_FLAG) { return sqf1(me, t2 PASS_REGS); - } // bad key? return false; @@ -850,8 +858,7 @@ static Int cont_yap_flag(USES_REGS1) { Term modt = CurrentModule; tflag = Yap_StripModule(tflag, &modt); while (i != gmax && i != UNKNOWN_FLAG && i != CHARACTER_ESCAPES_FLAG && - i != BACK_QUOTES_FLAG && - i != SINGLE_QUOTES_FLAG && + i != BACK_QUOTES_FLAG && i != SINGLE_QUOTES_FLAG && i != DOUBLE_QUOTES_FLAG) i++; if (i == gmax) @@ -1056,14 +1063,16 @@ void Yap_setModuleFlags(ModEntry *new, ModEntry *cme) { Atom at = new->AtomOfME; if (at == AtomProlog || CurrentModule == PROLOG_MODULE) { - new->flags = - M_SYSTEM | UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES | BCKQ_STRING |SNGQ_ATOM; + new->flags = M_SYSTEM | UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES | + BCKQ_STRING | SNGQ_ATOM; if (at == AtomUser) - new->flags = UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES | BCKQ_STRING |SNGQ_ATOM; + new->flags = + UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES | BCKQ_STRING | SNGQ_ATOM; } else if (cme && cme->flags && cme != new) { new->flags = cme->flags; } else { - new->flags = (UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES | BCKQ_STRING |SNGQ_ATOM); + new->flags = + (UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES | BCKQ_STRING | SNGQ_ATOM); } // printf("cme=%s new=%s flags=%x\n",cme,at->StrOfAE,new->flags); } @@ -1391,8 +1400,9 @@ static bool setInitialValue(bool bootstrap, flag_func f, const char *s, return false; } CACHE_REGS - const char *us = (const char *)s; - t0 = Yap_BufferToTermWithPrioBindings(us, TermNil, 0L, strlen(s) + 1, GLOBAL_MaxPriority); + const char *us = (const char *)s; + t0 = Yap_BufferToTermWithPrioBindings(us, TermNil, 0L, strlen(s) + 1, + GLOBAL_MaxPriority); if (!t0) return false; if (IsAtomTerm(t0) || IsIntTerm(t0)) { @@ -1439,8 +1449,9 @@ do_prolog_flag_property(Term tflag, xarg *args; prolog_flag_property_choices_t i; bool rc = true; - args = Yap_ArgList2ToVector(opts, prolog_flag_property_defs, - PROLOG_FLAG_PROPERTY_END, DOMAIN_ERROR_PROLOG_FLAG); + args = + Yap_ArgList2ToVector(opts, prolog_flag_property_defs, + PROLOG_FLAG_PROPERTY_END, DOMAIN_ERROR_PROLOG_FLAG); if (args == NULL) { Yap_Error(LOCAL_Error_TYPE, opts, NULL); return false; @@ -1527,9 +1538,8 @@ static Int cont_prolog_flag_property(USES_REGS1) { /* current_prolog_flag */ lab = MkAtomTerm(Yap_LookupAtom(local_flags_setup[i - gmax].name)); } else { if (i == UNKNOWN_FLAG || i == CHARACTER_ESCAPES_FLAG || - i == SINGLE_QUOTES_FLAG || - i == DOUBLE_QUOTES_FLAG || - i == BACK_QUOTES_FLAG) { + i == SINGLE_QUOTES_FLAG || i == DOUBLE_QUOTES_FLAG || + i == BACK_QUOTES_FLAG) { Term labs[2]; labs[0] = MkVarTerm(); labs[1] = MkAtomTerm(Yap_LookupAtom(global_flags_setup[i].name)); @@ -1607,8 +1617,9 @@ static Int do_create_prolog_flag(USES_REGS1) { prolog_flag_property_choices_t i; Term tflag = Deref(ARG1), tval = Deref(ARG2), opts = Deref(ARG3); - args = Yap_ArgList2ToVector(opts, prolog_flag_property_defs, - PROLOG_FLAG_PROPERTY_END, DOMAIN_ERROR_PROLOG_FLAG); + args = + Yap_ArgList2ToVector(opts, prolog_flag_property_defs, + PROLOG_FLAG_PROPERTY_END, DOMAIN_ERROR_PROLOG_FLAG); if (args == NULL) { Yap_Error(LOCAL_Error_TYPE, opts, NULL); return false; @@ -1660,15 +1671,15 @@ static Int do_create_prolog_flag(USES_REGS1) { } /** -* Init System Prolog flags. This is done in two phases: -* early on, it takes care of the atomic flags that are required by other -*modules; -* later, it looks at flags that are structured terms -* -* @param bootstrap: wether this is done before stack initialization, or -*afterwards. -* Complex terms can only be built in the second step. -*/ + * Init System Prolog flags. This is done in two phases: + * early on, it takes care of the atomic flags that are required by other + *modules; + * later, it looks at flags that are structured terms + * + * @param bootstrap: wether this is done before stack initialization, or + *afterwards. + * Complex terms can only be built in the second step. + */ void Yap_InitFlags(bool bootstrap) { CACHE_REGS @@ -1722,7 +1733,7 @@ void Yap_InitFlags(bool bootstrap) { */ Yap_InitCPredBack("prolog_flag", 3, 1, current_prolog_flag, cont_yap_flag, 0); - Yap_InitCPredBack("yap_flag", 3, 1, prolog_flag, cont_yap_flag, 0); + Yap_InitCPredBack("yap_flag", 3, 1, yap_flag, cont_yap_flag, 0); Yap_InitCPredBack("prolog_flag", 2, 1, current_prolog_flag2, cont_current_prolog_flag, 0); Yap_InitCPredBack("current_prolog_flag", 2, 1, current_prolog_flag2, diff --git a/C/fli_absmi_insts.h b/C/fli_absmi_insts.h index 371f5248c..4a08b62ec 100644 --- a/C/fli_absmi_insts.h +++ b/C/fli_absmi_insts.h @@ -56,7 +56,7 @@ CPredicate f = PREG->y_u.Osbpp.p->cs.f_code; PREG = NEXTOP(PREG, Osbpp); saveregs(); - d0 = (f)(PASS_REGS1); + d0 = f(PASS_REGS1); setregs(); #ifdef SHADOW_S SREG = Yap_REGS.S_; diff --git a/C/globals.c b/C/globals.c index ec328051b..aa21751bc 100644 --- a/C/globals.c +++ b/C/globals.c @@ -475,7 +475,7 @@ loop: goto overflow; } *ptf++ = AbsAppl(HR); - memcpy(HR, ap2, sizeof(CELL) * (3 + ap2[1])); + memmove(HR, ap2, sizeof(CELL) * (3 + ap2[1])); HR += ap2[1] + 3; break; default: { @@ -756,7 +756,7 @@ restart: res = -1; goto error_handler; } - memcpy(HR, ap, sizeof(CELL) * (3 + ap[1])); + memmove(HR, ap, sizeof(CELL) * (3 + ap[1])); HR += ap[1] + 3; break; default: { diff --git a/C/grow.c b/C/grow.c index 7b067941d..e80ee26f1 100755 --- a/C/grow.c +++ b/C/grow.c @@ -205,13 +205,13 @@ CopyLocalAndTrail( USES_REGS1 ) static void IncrementalCopyStacksFromWorker( USES_REGS1 ) { - memcpy((void *) PtoGloAdjust((CELL *)LOCAL_start_global_copy), + memmove((void *) PtoGloAdjust((CELL *)LOCAL_start_global_copy), (void *) (LOCAL_start_global_copy), (size_t) (LOCAL_end_global_copy - LOCAL_start_global_copy)); - memcpy((void *) PtoLocAdjust((CELL *)LOCAL_start_local_copy), + memmove((void *) PtoLocAdjust((CELL *)LOCAL_start_local_copy), (void *) LOCAL_start_local_copy, (size_t) (LOCAL_end_local_copy - LOCAL_start_local_copy)); - memcpy((void *) PtoTRAdjust((tr_fr_ptr)LOCAL_start_trail_copy), + memmove((void *) PtoTRAdjust((tr_fr_ptr)LOCAL_start_trail_copy), (void *) (LOCAL_start_trail_copy), (size_t) (LOCAL_end_trail_copy - LOCAL_start_trail_copy)); } diff --git a/C/index.c b/C/index.c index b9a8a0921..03e9d41b0 100755 --- a/C/index.c +++ b/C/index.c @@ -825,7 +825,7 @@ static inline int smaller_or_eq(Term t1, Term t2) { } static inline void clcpy(ClauseDef *d, ClauseDef *s) { - memcpy((void *)d, (void *)s, sizeof(ClauseDef)); + memmove((void *)d, (void *)s, sizeof(ClauseDef)); } static void insort(ClauseDef base[], CELL *p, CELL *q, int my_p) { @@ -2670,7 +2670,7 @@ static ClauseDef *copy_clauses(ClauseDef *max0, ClauseDef *min0, CELL *top, save_machine_regs(); siglongjmp(cint->CompilerBotch, 4); } - memcpy((void *)top, (void *)min0, sz); + memmove((void *)top, (void *)min0, sz); return (ClauseDef *)top; } diff --git a/C/init.c b/C/init.c index 5edb89716..c9c20ad38 100755 --- a/C/init.c +++ b/C/init.c @@ -301,7 +301,7 @@ bool Yap_dup_op(OpEntry *op, ModEntry *she) { OpEntry *info = (OpEntry *)Yap_AllocAtomSpace(sizeof(OpEntry)); if (!info) return false; - memcpy(info, op, sizeof(OpEntry)); + memmove(info, op, sizeof(OpEntry)); info->NextForME = she->OpForME; she->OpForME = info; info->OpModule = MkAtomTerm(she->AtomOfME); @@ -1162,7 +1162,7 @@ void Yap_init_yapor_workers(void) { worker_id = proc; Yap_remap_yapor_memory(); LOCAL = REMOTE(worker_id); - memcpy(REMOTE(worker_id), REMOTE(0), sizeof(struct worker_local)); + memmove(REMOTE(worker_id), REMOTE(0), sizeof(struct worker_local)); InitWorker(worker_id); break; } else diff --git a/C/scanner.c b/C/scanner.c index 9555bd7d1..f401e94f5 100755 --- a/C/scanner.c +++ b/C/scanner.c @@ -447,7 +447,7 @@ static void Yap_setCurrentSourceLocation(struct stream_desc *s) { if (s->status & Pipe_Stream_f) LOCAL_SourceFileName = AtomPipe; else if (s->status & InMemory_Stream_f) - LOCAL_SourceFileName = AtomCharsio; + LOCAL_SourceFileName = s->name; else LOCAL_SourceFileName = s->name; LOCAL_SourceFileLineno = s->linecount; diff --git a/C/stack.c b/C/stack.c index 8269b9beb..b719eaf95 100644 --- a/C/stack.c +++ b/C/stack.c @@ -1808,7 +1808,7 @@ void Yap_dump_stack(void) { yap_error_class_number classno = Yap_errorClass(errnbr); fprintf(stderr, "%% Error STATUS: %s/%s\n\n", Yap_errorName(errnbr), - Yap_errorName(classno)); + Yap_errorClassName(classno)); fprintf(stderr, "%% Execution mode\n"); if (LOCAL_PrologMode & BootMode) diff --git a/C/text.c b/C/text.c index eb6000f34..b1b78aeb9 100644 --- a/C/text.c +++ b/C/text.c @@ -199,7 +199,7 @@ const void *MallocExportAsRO(const void *pt USES_REGS) { return NULL; size_t sz = o->sz; release_block(o); - memcpy((void *)o, pt, sz); + memmove((void *)o, pt, sz); return realloc((void *)o, sz); } @@ -215,10 +215,7 @@ void *Yap_InitTextAllocator(void) { return new; } -static size_t MaxTmp(USES_REGS1) { - - return 1025; -} +static size_t MaxTmp(USES_REGS1) { return 1025; } static Term Globalize(Term v USES_REGS) { if (!IsVarTerm(v = Deref(v))) { @@ -231,7 +228,8 @@ static Term Globalize(Term v USES_REGS) { return v; } -static void *codes2buf(Term t0, void *b0, bool *get_codes USES_REGS) { +static void *codes2buf(Term t0, void *b0, bool get_codes, + bool fixed USES_REGS) { unsigned char *st0, *st, ar[16]; Term t = t0; size_t length = 0; @@ -241,11 +239,19 @@ static void *codes2buf(Term t0, void *b0, bool *get_codes USES_REGS) { st0[0] = 0; return st0; } - if (!IsPairTerm(t)) + if (!IsPairTerm(t)) { + Yap_ThrowError(TYPE_ERROR_LIST, t, "scanning list of codes"); return NULL; + } bool codes = IsIntegerTerm(HeadOfTerm(t)); - if (get_codes) - *get_codes = codes; + if (get_codes != codes && fixed) { + if (codes) { + Yap_ThrowError(TYPE_ERROR_INTEGER, HeadOfTerm(t), + "scanning list of codes"); + } else { + Yap_ThrowError(TYPE_ERROR_ATOM, HeadOfTerm(t), "scanning list of atoms"); + } + } if (codes) { while (IsPairTerm(t)) { Term hd = HeadOfTerm(t); @@ -259,7 +265,8 @@ static void *codes2buf(Term t0, void *b0, bool *get_codes USES_REGS) { } Int code = IntegerOfTerm(hd); if (code < 0) { - Yap_ThrowError(TYPE_ERROR_CHARACTER_CODE, hd, "scanning list of codes"); + Yap_ThrowError(REPRESENTATION_ERROR_CHARACTER_CODE, hd, + "scanning list of character codes, found %d", code); return NULL; } length += put_utf8(ar, code); @@ -368,26 +375,21 @@ static void *slice(size_t min, size_t max, const unsigned char *buf USES_REGS); static unsigned char *Yap_ListOfCodesToBuffer(unsigned char *buf, Term t, seq_tv_t *inp USES_REGS) { - bool codes; - unsigned char *nbuf = codes2buf(t, buf, &codes PASS_REGS); - if (!codes) - return NULL; + bool codes = true, fixed = true; + unsigned char *nbuf = codes2buf(t, buf, codes, fixed PASS_REGS); return nbuf; } static unsigned char *Yap_ListOfAtomsToBuffer(unsigned char *buf, Term t, seq_tv_t *inp USES_REGS) { - bool codes; - unsigned char *nbuf = codes2buf(t, buf, &codes PASS_REGS); - if (codes) - return NULL; + bool codes = false; + unsigned char *nbuf = codes2buf(t, buf, codes, true PASS_REGS); return nbuf; } static unsigned char *Yap_ListToBuffer(unsigned char *buf, Term t, seq_tv_t *inp USES_REGS) { - unsigned char *nbuf = codes2buf(t, buf, NULL PASS_REGS); - return nbuf; + return codes2buf(t, buf, NULL, false PASS_REGS); } #if USE_GEN_TYPE_ERROR @@ -418,8 +420,10 @@ static yap_error_number gen_type_error(int flags) { // static int cnt; unsigned char *Yap_readText(seq_tv_t *inp USES_REGS) { - +#define POPRET(x) return pop_output_text_stack(lvl, x) int lvl = push_text_stack(); + char *out = NULL; + yap_error_number err0 = LOCAL_Error_TYPE; /* we know what the term is */ if (!(inp->type & (YAP_STRING_CHARS | YAP_STRING_WCHARS))) { if (!(inp->type & YAP_STRING_TERM)) { @@ -431,128 +435,131 @@ unsigned char *Yap_readText(seq_tv_t *inp USES_REGS) { LOCAL_Error_TYPE = TYPE_ERROR_STRING; } else if (!IsPairOrNilTerm(inp->val.t) && !IsStringTerm(inp->val.t) && inp->type == (YAP_STRING_ATOMS_CODES | YAP_STRING_STRING)) { - LOCAL_Error_TYPE = TYPE_ERROR_LIST; + LOCAL_ActiveError->errorRawTerm = inp->val.t; } else if (!IsPairOrNilTerm(inp->val.t) && !IsStringTerm(inp->val.t) && !IsAtomTerm(inp->val.t) && !(inp->type & YAP_STRING_DATUM)) { LOCAL_Error_TYPE = TYPE_ERROR_TEXT; } } - if (LOCAL_Error_TYPE != YAP_NO_ERROR) { - if (inp->val.uc != NULL) { - LOCAL_ActiveError->errorRawTerm = MkUStringTerm(inp->val.uc); - - } - Yap_ThrowError(LOCAL_Error_TYPE, LOCAL_ActiveError->errorRawTerm, "Converting to text from term "); - return NULL; + if (err0 != LOCAL_Error_TYPE) { + Yap_ThrowError(LOCAL_Error_TYPE, inp->val.t, "while reading text in"); + } } - } - if (IsAtomTerm(inp->val.t) && inp->type & YAP_STRING_ATOM) { // this is a term, extract to a buffer, and representation is wide // Yap_DebugPlWriteln(inp->val.t); Atom at = AtomOfTerm(inp->val.t); if (RepAtom(at)->UStrOfAE[0] == 0) { - unsigned char *o = Malloc(4); - memset(o, 0, 4); - return pop_output_text_stack(lvl, o); + out = Malloc(4); + memset(out, 0, 4); + POPRET( out ); } if (inp->type & YAP_STRING_WITH_BUFFER) { pop_text_stack(lvl); return at->UStrOfAE; } - size_t sz = strlen(at->StrOfAE); - void *o = Malloc(sz + 1); - strcpy(o, at->StrOfAE); - return pop_output_text_stack(lvl, o); + { + size_t sz = strlen(at->StrOfAE); + out = Malloc(sz + 1); + strcpy(out, at->StrOfAE); + POPRET( out ); + } } if (IsStringTerm(inp->val.t) && inp->type & YAP_STRING_STRING) { // this is a term, extract to a buffer, and representation is wide // Yap_DebugPlWriteln(inp->val.t); const char *s = StringOfTerm(inp->val.t); if (s[0] == 0) { - char *o = Malloc(4); - memset(o, 0, 4); - return pop_output_text_stack(lvl, o); + out = Malloc(4); + memset(out, 0, 4); + POPRET( out ); + } + if (inp->type & YAP_STRING_WITH_BUFFER) { + pop_text_stack(lvl); + return (unsigned char *)UStringOfTerm(inp->val.t); + } + { + inp->type |= YAP_STRING_IN_TMP; + size_t sz = strlen(s); + out = Malloc(sz + 1); + strcpy(out, s); + POPRET( out ); + } + } else if (IsPairOrNilTerm(inp->val.t)) { + if (((inp->type & (YAP_STRING_CODES | YAP_STRING_ATOMS)) == + (YAP_STRING_CODES | YAP_STRING_ATOMS))) { + // Yap_DebugPlWriteln(inp->val.t); + out = (char *)Yap_ListToBuffer(NULL, inp->val.t, inp PASS_REGS); + POPRET( out ); + // this is a term, extract to a sfer, and representation is wide + } + if (inp->type & YAP_STRING_CODES) { + // Yap_DebugPlWriteln(inp->val.t); + out = (char *)Yap_ListOfCodesToBuffer(NULL, inp->val.t, inp PASS_REGS); + // this is a term, extract to a sfer, and representation is wide + POPRET( out ); + } + if (inp->type & YAP_STRING_ATOMS) { + // Yap_DebugPlWriteln(inp->val.t); + out = (char *)Yap_ListOfAtomsToBuffer(NULL, inp->val.t, inp PASS_REGS); + // this is a term, extract to a buffer, and representation is wide + POPRET( out ); } - if (inp->type & YAP_STRING_WITH_BUFFER) - return (unsigned char *)UStringOfTerm(inp->val.t); - inp->type |= YAP_STRING_IN_TMP; - size_t sz = strlen(s); - char *o = Malloc(sz + 1); - strcpy(o, s); - return pop_output_text_stack(lvl, o); - } - if (((inp->type & (YAP_STRING_CODES | YAP_STRING_ATOMS)) == - (YAP_STRING_CODES | YAP_STRING_ATOMS)) && - IsPairOrNilTerm(inp->val.t)) { - // Yap_DebugPlWriteln(inp->val.t); - return pop_output_text_stack( - lvl, Yap_ListToBuffer(NULL, inp->val.t, inp PASS_REGS)); - // this is a term, extract to a sfer, and representation is wide - } - if (inp->type & YAP_STRING_CODES && IsPairOrNilTerm(inp->val.t)) { - // Yap_DebugPlWriteln(inp->val.t); - return pop_output_text_stack( - lvl, Yap_ListOfCodesToBuffer(NULL, inp->val.t, inp PASS_REGS)); - // this is a term, extract to a sfer, and representation is wide - } - if (inp->type & YAP_STRING_ATOMS && IsPairOrNilTerm(inp->val.t)) { - // Yap_DebugPlWriteln(inp->val.t); - return pop_output_text_stack( - lvl, Yap_ListOfAtomsToBuffer(NULL, inp->val.t, inp PASS_REGS)); - // this is a term, extract to a buffer, and representation is wide } if (inp->type & YAP_STRING_INT && IsIntegerTerm(inp->val.t)) { // ASCII, so both LATIN1 and UTF-8 // Yap_DebugPlWriteln(inp->val.t); - char *s; - s = Malloc(2 * MaxTmp(PASS_REGS1)); - if (snprintf(s, MaxTmp(PASS_REGS1) - 1, Int_FORMAT, + out = Malloc(2 * MaxTmp(PASS_REGS1)); + if (snprintf(out, MaxTmp(PASS_REGS1) - 1, Int_FORMAT, IntegerOfTerm(inp->val.t)) < 0) { - AUX_ERROR(inp->val.t, 2 * MaxTmp(PASS_REGS1), s, char); + AUX_ERROR(inp->val.t, 2 * MaxTmp(PASS_REGS1), out, char); } - return pop_output_text_stack(lvl, s); + POPRET( out ); } if (inp->type & YAP_STRING_FLOAT && IsFloatTerm(inp->val.t)) { - char *s; - // Yap_DebugPlWriteln(inp->val.t); - if (!Yap_FormatFloat(FloatOfTerm(inp->val.t), &s, 1024)) { + out = Malloc(2 * MaxTmp(PASS_REGS1)); + if (!Yap_FormatFloat(FloatOfTerm(inp->val.t), &out, 1024)) { pop_text_stack(lvl); return NULL; } - return pop_output_text_stack(lvl, s); - } + POPRET(out); + } #if USE_GMP if (inp->type & YAP_STRING_BIG && IsBigIntTerm(inp->val.t)) { // Yap_DebugPlWriteln(inp->val.t); - char *s; - s = Malloc(MaxTmp()); - if (!Yap_mpz_to_string(Yap_BigIntOfTerm(inp->val.t), s, MaxTmp() - 1, 10)) { - AUX_ERROR(inp->val.t, MaxTmp(PASS_REGS1), s, char); + out = Malloc(MaxTmp()); + if (!Yap_mpz_to_string(Yap_BigIntOfTerm(inp->val.t), out, MaxTmp() - 1, + 10)) { + AUX_ERROR(inp->val.t, MaxTmp(PASS_REGS1), out, char); } - return inp->val.uc = pop_output_text_stack(lvl, s); + POPRET(out); } #endif if (inp->type & YAP_STRING_TERM) { - // Yap_DebugPlWriteln(inp->val.t); - char *s = (char *)Yap_TermToBuffer(inp->val.t, ENC_ISO_UTF8, 0); - return inp->val.uc = pop_output_text_stack(lvl, s); - } - if (inp->type & YAP_STRING_CHARS) { pop_text_stack(lvl); - if (inp->enc == ENC_ISO_LATIN1) { - return latin2utf8(inp); - } else if (inp->enc == ENC_ISO_ASCII) { - return inp->val.uc; - } else { // if (inp->enc == ENC_ISO_UTF8) { + return Yap_TermToBuffer(inp->val.t, 0); + } + + if (inp->type & YAP_STRING_CHARS) { + if (inp->enc == ENC_ISO_ASCII) { + pop_text_stack(lvl); return inp->val.uc; } + + if (inp->enc == ENC_ISO_LATIN1) { + POPRET( (char*)latin2utf8(inp)); + } + + if (inp->enc == ENC_ISO_UTF8) { + pop_text_stack(lvl); + return inp->val.c; + } } - pop_text_stack(lvl); if (inp->type & YAP_STRING_WCHARS) { // printf("%S\n",inp->val.w); - return wchar2utf8(inp); + POPRET( (char *)wchar2utf8(inp) ); } + pop_text_stack(lvl); return NULL; } @@ -681,16 +688,16 @@ static Term write_codes(void *s0, seq_tv_t *out USES_REGS) { static Atom write_atom(void *s0, seq_tv_t *out USES_REGS) { unsigned char *s = s0; int32_t ch; - size_t leng = strlen(s0); - if (leng == 0) { + if (s[0] == '\0') { return Yap_LookupAtom(""); } + size_t leng = strlen(s0); if (strlen_utf8(s0) <= leng) { return Yap_LookupAtom(s0); } else { size_t n = get_utf8(s, -1, &ch); unsigned char *buf = Malloc(n + 1); - memcpy(buf, s0, n + 1); + memmove(buf, s0, n + 1); return Yap_ULookupAtom(buf); } } @@ -921,7 +928,7 @@ bool Yap_CVT_Text(seq_tv_t *inp, seq_tv_t *out USES_REGS) { const unsigned char *ptr = skip_utf8(buf, out->max); size_t diff = (ptr - buf); char *nbuf = Malloc(diff + 1); - memcpy(nbuf, buf, diff); + memmove(nbuf, buf, diff); nbuf[diff] = '\0'; leng = diff; } diff --git a/C/text.c.new b/C/text.c.new index 7c1d67f41..e4326e3d9 100644 --- a/C/text.c.new +++ b/C/text.c.new @@ -85,7 +85,7 @@ void *protected_pop_text_stack(int i, void *protected, bool tmp, out = LOCAL_FileNameBuf; else out = p; - memcpy(out, protected, sz); + memmove(out, protected, sz); } else { free(p); } @@ -661,7 +661,7 @@ static Atom write_atom(void *s0, seq_tv_t *out, size_t leng USES_REGS) { return Yap_LookupAtom(s0); } else { unsigned char *buf = Malloc(leng + 1); - memcpy(buf, s0, leng); + memmove(buf, s0, leng); buf[leng] = \0; return Yap_ULookupAtom(buf); } @@ -872,7 +872,7 @@ bool Yap_CVT_Text(seq_tv_t *inp, seq_tv_t *out USES_REGS) { size_t max_s = skip_utf8( buf, out-> max )-buf; if (max_s < leng_s) { char *nbuf = Malloc(max_s + 1); - memcpy(nbuf, buf, max_s); + memmove(nbuf, buf, max_s); nbuf[max_s] = '\0'; leng_s = out->max; } diff --git a/C/tracer.c b/C/tracer.c index 301640d5f..c4de2fb23 100644 --- a/C/tracer.c +++ b/C/tracer.c @@ -87,7 +87,7 @@ static char *send_tracer_message(char *start, char *name, arity_t arity, continue; } } - const char *sn = Yap_TermToBuffer(args[i], LOCAL_encoding, + const char *sn = Yap_TermToBuffer(args[i], Quote_illegal_f | Handle_vars_f); size_t sz; if (sn == NULL) { diff --git a/C/utilpreds.c b/C/utilpreds.c index b1b8e9f88..fab75ad12 100644 --- a/C/utilpreds.c +++ b/C/utilpreds.c @@ -182,7 +182,7 @@ copy_complex_term(CELL *pt0, CELL *pt0_end, int share, int newattvs, CELL *ptf, if (HR+sz > ASP - 2048) { goto overflow; } - memcpy((void *)HR, (void *)ap2, sz*sizeof(CELL)); + memmove((void *)HR, (void *)ap2, sz*sizeof(CELL)); HR += sz; } else { *ptf++ = d0; /* you can just copy other extensions. */ @@ -845,7 +845,7 @@ export_term_to_buffer(Term inpt, char *buf, char *bptr, CELL *t0 , CELL *tf, siz if (buf + len < (char *)((CELL *)td + (tf-t0))) { return FALSE; } - memcpy((void *)td, (void *)t0, (tf-t0)* sizeof(CELL)); + memmove((void *)td, (void *)t0, (tf-t0)* sizeof(CELL)); bf[0] = (td-buf); bf[1] = (tf-t0); bf[2] = inpt; @@ -945,7 +945,7 @@ export_complex_term(Term tf, CELL *pt0, CELL *pt0_end, char * buf, size_t len0, if (HR+sz > ASP - 2048) { goto overflow; } - memcpy((void *)HR, (void *)ap2, sz*sizeof(CELL)); + memmove((void *)HR, (void *)ap2, sz*sizeof(CELL)); HR += sz; continue; } @@ -1263,7 +1263,7 @@ Yap_ImportTerm(char * buf) { return 0L; } } - memcpy(HR, buf+bc[0], sizeof(CELL)*sz); + memmove(HR, buf+bc[0], sizeof(CELL)*sz); if (IsApplTerm(tinp)) { tret = AbsAppl(HR); import_compound(HR, (char *)HR, buf, HR); @@ -3476,7 +3476,7 @@ hash_complex_term(register CELL *pt0, *st++ = LongIntOfTerm(d0); break; case (CELL)FunctorString: - memcpy(st, RepAppl(d0), (3+RepAppl(d0)[1])*sizeof(CELL)); + memmove(st, RepAppl(d0), (3+RepAppl(d0)[1])*sizeof(CELL)); st += 3+RepAppl(d0)[1]; break; #ifdef USE_GMP @@ -3491,7 +3491,7 @@ hash_complex_term(register CELL *pt0, goto global_overflow; } /* then the actual number */ - memcpy((void *)(st+1), (void *)(pt+1), sz); + memmove((void *)(st+1), (void *)(pt+1), sz); st = st+sz/CellSize; } break; diff --git a/C/write.c b/C/write.c index a09895663..9abc1af3f 100644 --- a/C/write.c +++ b/C/write.c @@ -384,9 +384,7 @@ int Yap_FormatFloat(Float f, char **s, size_t sz) { wglb.lw = separator; wglb.stream = GLOBAL_Stream + sno; wrputf(f, &wglb); - so = Yap_MemExportStreamPtr(sno); - *s = BaseMalloc(strlen(so) + 1); - strcpy(*s, so); + *s = Yap_MemExportStreamPtr(sno); Yap_CloseStream(sno); return true; } @@ -1255,28 +1253,3 @@ void Yap_plwrite(Term t, StreamDesc *mywrite, int max_depth, int flags, pop_text_stack(lvl); } -char *Yap_TermToBuffer(Term t, encoding_t enc, int flags) { - CACHE_REGS - int sno = Yap_open_buf_write_stream(enc, flags); - const char *sf; - - if (sno < 0) - return NULL; - if (t == 0) - return NULL; - else - t = Deref(t); - if (enc) - GLOBAL_Stream[sno].encoding = enc; - else - GLOBAL_Stream[sno].encoding = LOCAL_encoding; - GLOBAL_Stream[sno].status |= CloseOnException_Stream_f; - Yap_plwrite(t, GLOBAL_Stream + sno, 0, flags, GLOBAL_MaxPriority); - - sf = Yap_MemExportStreamPtr(sno); - size_t len = strlen(sf); - char *new = malloc(len + 1); - strcpy(new, sf); - Yap_CloseStream(sno); - return new; -} diff --git a/C/yap-args.c b/C/yap-args.c index 871b8c292..e7be80153 100755 --- a/C/yap-args.c +++ b/C/yap-args.c @@ -161,8 +161,7 @@ static bool consult(const char *b_file USES_REGS) { /* consult in C */ int lvl = push_text_stack(); - char *full = Malloc(YAP_FILENAME_MAX + 1); - full[0] = '\0'; + char *full; /* the consult mode does not matter here, really */ if ((osno = Yap_CheckAlias(AtomLoopStream)) < 0) { osno = 0; @@ -204,17 +203,21 @@ static bool consult(const char *b_file USES_REGS) { } else { YAP_CompileClause(t); } - } while (true); yap_error_descriptor_t *errd; if ((errd = Yap_GetException(LOCAL_ActiveError))) { fprintf(stderr, "%s:%ld:0: Error %s %s Found\n", errd->errorFile, (long int) errd->errorLine, errd->classAsText, errd->errorAsText); } + } while (true); BACKUP_MACHINE_REGS(); YAP_EndConsult(c_stream, &osno, full); - pop_text_stack(lvl); - return true; + if (!Yap_AddAlias(AtomLoopStream, osno)) { + pop_text_stack(lvl); + return false; + } + pop_text_stack(lvl); + return true; } /// diff --git a/CMakeLists.txt b/CMakeLists.txt index 1ae14e4ae..2365fd4bd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -554,7 +554,7 @@ IF (WITH_PYTHON) ENDIF (WITH_PYTHON) option(WITH_R - "Allow YAP->R" ON) + "Use R Interface" ON) IF (WITH_R) include_directories(packages/real ) diff --git a/CXX/yapi.cpp b/CXX/yapi.cpp index 2642befef..d955eada6 100644 --- a/CXX/yapi.cpp +++ b/CXX/yapi.cpp @@ -19,7 +19,7 @@ extern "C" { #include "YapInterface.h" #include "iopreds.h" -X_API char *Yap_TermToBuffer(Term t, encoding_t encodingp, int flags); +X_API char *Yap_TermToBuffer(Term t, int flags); X_API void YAP_UserCPredicate(const char *, YAP_UserCPred, arity_t arity); X_API void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, arity_t, @@ -30,35 +30,32 @@ X_API void YAP_UserBackCPredicate(const char *, YAP_UserCPred, YAP_UserCPred, #if YAP_PYTHON X_API bool do_init_python(void); #endif - - } -static void YAPCatchError() - { - if (LOCAL_CommittedError != nullptr && - LOCAL_CommittedError->errorNo != YAP_NO_ERROR ) { - // Yap_PopTermFromDB(info->errorTerm); - // throw throw YAPError( ); - Term es[2]; - es[0] = TermError; - es[1] = MkErrorTerm(LOCAL_CommittedError); - Functor f = Yap_MkFunctor(Yap_LookupAtom("print_message"), 2); - YAP_RunGoalOnce(Yap_MkApplTerm(f, 2, es)); - // Yap_PopTermFromDB(info->errorTerm); - // throw throw YAPError( SOURCE(), ); - } else if (LOCAL_ActiveError != nullptr && - LOCAL_ActiveError->errorNo != YAP_NO_ERROR ) { - // Yap_PopTermFromDB(info->errorTerm); - // throw throw YAPError( ); - Term es[2]; - es[0] = TermError; - es[1] = MkErrorTerm(LOCAL_ActiveError); - Functor f = Yap_MkFunctor(Yap_LookupAtom("print_message"), 2); - YAP_RunGoalOnce(Yap_MkApplTerm(f, 2, es)); - // Yap_PopTermFromDB(info->errorTerm); - // throw throw YAPError( SOURCE(), ); - } +static void YAPCatchError() { + if (LOCAL_CommittedError != nullptr && + LOCAL_CommittedError->errorNo != YAP_NO_ERROR) { + // Yap_PopTermFromDB(info->errorTerm); + // throw throw YAPError( ); + Term es[2]; + es[0] = TermError; + es[1] = MkErrorTerm(LOCAL_CommittedError); + Functor f = Yap_MkFunctor(Yap_LookupAtom("print_message"), 2); + YAP_RunGoalOnce(Yap_MkApplTerm(f, 2, es)); + // Yap_PopTermFromDB(info->errorTerm); + // throw throw YAPError( SOURCE(), ); + } else if (LOCAL_ActiveError != nullptr && + LOCAL_ActiveError->errorNo != YAP_NO_ERROR) { + // Yap_PopTermFromDB(info->errorTerm); + // throw throw YAPError( ); + Term es[2]; + es[0] = TermError; + es[1] = MkErrorTerm(LOCAL_ActiveError); + Functor f = Yap_MkFunctor(Yap_LookupAtom("print_message"), 2); + YAP_RunGoalOnce(Yap_MkApplTerm(f, 2, es)); + // Yap_PopTermFromDB(info->errorTerm); + // throw throw YAPError( SOURCE(), ); + } } YAPPredicate::YAPPredicate(Term &t, Term &tmod, CELL *&ts, const char *pname) { @@ -189,14 +186,8 @@ YAPStringTerm::YAPStringTerm(char *s) { // build string BACKUP_H(); CACHE_REGS - seq_tv_t inp, out; - inp.val.c = s; - inp.type = YAP_STRING_CHARS; - out.type = YAP_STRING_STRING; - if (Yap_CVT_Text(&inp, &out PASS_REGS)) - mk(out.val.t); - else - t = 0L; + Term ts = MkStringTerm(s); + mk(ts); RECOVER_H(); } @@ -340,7 +331,7 @@ std::vector YAPPairTerm::listToArray() { if (l < 0) { throw YAPError(SOURCE(), TYPE_ERROR_LIST, (t), nullptr); } - std::vector o = * new std::vector(l); + std::vector o = *new std::vector(l); int i = 0; Term t = gt(); while (t != TermNil) { @@ -489,7 +480,7 @@ const char *YAPAtom::getName(void) { return Yap_AtomToUTF8Text(a); } void YAPQuery::openQuery() { CACHE_REGS - if (ap == NULL || ap->OpcodeOfPred == UNDEF_OPCODE) { + if (ap == NULL || ap->OpcodeOfPred == UNDEF_OPCODE) { ap = rewriteUndefQuery(); } setNext(); @@ -518,7 +509,7 @@ bool YAPEngine::call(YAPPredicate ap, YAPTerm ts[]) { YAPCatchError(); Yap_CloseHandles(q.CurSlot); - pop_text_stack(q.lvl+1); + pop_text_stack(q.lvl + 1); RECOVER_MACHINE_REGS(); return result; @@ -528,45 +519,46 @@ bool YAPEngine::mgoal(Term t, Term tmod, bool release) { #if YAP_PYTHON // PyThreadState *_save; - //std::cerr << "mgoal " << YAPTerm(t).text() << "\n"; // _save = PyEval_SaveThread(); #endif CACHE_REGS BACKUP_MACHINE_REGS(); Term *ts = nullptr; - q.CurSlot = Yap_StartSlots(); - q.p = P; - q.cp = CP; - PredEntry *ap = nullptr; - if (IsStringTerm(tmod)) - tmod = MkAtomTerm(Yap_LookupAtom(StringOfTerm(tmod))); - YAPPredicate *p = new YAPPredicate(t, tmod, ts, "C++"); - if (p == nullptr || (ap = p->ap) == nullptr || - ap->OpcodeOfPred == UNDEF_OPCODE) { - ap = rewriteUndefEngineQuery(ap, t, tmod); - } - if (IsApplTerm(t)) - ts = RepAppl(t) + 1; - else if (IsPairTerm(t)) - ts = RepPair(t); - /* legal ap */ - arity_t arity = ap->ArityOfPE; + q.CurSlot = Yap_StartSlots(); + q.p = P; + q.cp = CP; + PredEntry *ap = nullptr; + if (IsStringTerm(tmod)) + tmod = MkAtomTerm(Yap_LookupAtom(StringOfTerm(tmod))); + YAPPredicate *p = new YAPPredicate(t, tmod, ts, "C++"); + if (p == nullptr || (ap = p->ap) == nullptr || + ap->OpcodeOfPred == UNDEF_OPCODE) { + ap = rewriteUndefEngineQuery(ap, t, tmod); + } + if (IsApplTerm(t)) + ts = RepAppl(t) + 1; + else if (IsPairTerm(t)) + ts = RepPair(t); + /* legal ap */ + arity_t arity = ap->ArityOfPE; - for (arity_t i = 0; i < arity; i++) { - XREGS[i + 1] = ts[i]; - } - ts = nullptr; - bool result; - // allow Prolog style exception handling - // don't forget, on success these guys may create slots - //__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec "); + for (arity_t i = 0; i < arity; i++) { + XREGS[i + 1] = ts[i]; + } + ts = nullptr; + bool result; + // allow Prolog style exception handling + // don't forget, on success these guys may create slots + //__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec "); - result = (bool)YAP_EnterGoal(ap, nullptr, &q); - YAP_LeaveGoal(result && !release, &q); - // PyEval_RestoreThread(_save); - RECOVER_MACHINE_REGS(); - return result; + result = (bool)YAP_EnterGoal(ap, nullptr, &q); + //std::cerr << "mgoal " << YAPTerm(t).text() << "\n"; + + YAP_LeaveGoal(result && !release, &q); + // PyEval_RestoreThread(_save); + RECOVER_MACHINE_REGS(); + return result; } /** * called when a query must be terminated and its state fully recovered, @@ -672,31 +664,29 @@ goal = YAPApplTerm(f, nts); } #endif - YAPQuery::YAPQuery(YAPPredicate p, YAPTerm ts[]) : YAPPredicate(p.ap) { BACKUP_MACHINE_REGS(); try { arity_t arity = p.ap->ArityOfPE; - if (arity) { - goal = YAPApplTerm(YAPFunctor(p.ap->FunctorOfPred), ts).term(); - for (arity_t i = 0; i < arity; i++) - XREGS[i + 1] = ts[i].term(); - openQuery(); - } else { - goal = MkAtomTerm((Atom)(p.ap->FunctorOfPred)); - openQuery(); + if (arity) { + goal = YAPApplTerm(YAPFunctor(p.ap->FunctorOfPred), ts).term(); + for (arity_t i = 0; i < arity; i++) + XREGS[i + 1] = ts[i].term(); + openQuery(); + } else { + goal = MkAtomTerm((Atom)(p.ap->FunctorOfPred)); + openQuery(); + } + names = TermNil; + } catch (...) { } - names = TermNil; -} catch (...) { - - } -RECOVER_MACHINE_REGS(); + RECOVER_MACHINE_REGS(); } bool YAPQuery::next() { CACHE_REGS bool result = false; - //std::cerr << "next " << YAPTerm(goal).text() << "\n"; + // std::cerr << "next " << YAPTerm(goal).text() << "\n"; sigjmp_buf buf, *oldp = LOCAL_RestartEnv; e = nullptr; @@ -708,6 +698,7 @@ bool YAPQuery::next() { __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec "); if (q_state == 0) { + // Yap_do_low_level_trace = 1; result = (bool)YAP_EnterGoal(ap, nullptr, &q_h); } else { LOCAL_AllowRestart = q_open; @@ -715,19 +706,18 @@ bool YAPQuery::next() { } q_state = 1; __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "out %d", result); -if (!result) { + if (!result) { YAP_LeaveGoal(result, &q_h); q_open = false; } - YAPCatchError(); + YAPCatchError(); RECOVER_MACHINE_REGS(); LOCAL_RestartEnv = oldp; return result; } PredEntry *YAPQuery::rewriteUndefQuery() { - ARG1 = goal = Yap_SaveTerm(Yap_MkApplTerm(FunctorCall - , 1, &goal)); + ARG1 = goal = Yap_SaveTerm(Yap_MkApplTerm(FunctorCall, 1, &goal)); return ap = PredCall; } @@ -899,7 +889,7 @@ PredEntry *YAPPredicate::getPred(Term &t, CELL *&out) { ap = RepPredProp(PredPropByAtom(AtomOfTerm(t), m)); return ap; } else if (IsPairTerm(t)) { - Term ts[2], *s = ( out ? out : ts ); + Term ts[2], *s = (out ? out : ts); Functor FunctorConsult = Yap_MkFunctor(Yap_LookupAtom("consult"), 1); s[1] = t; s[0] = m; @@ -914,7 +904,7 @@ PredEntry *YAPPredicate::getPred(Term &t, CELL *&out) { } else { ap = RepPredProp(PredPropByFunc(f, m)); if (out) - memcpy( out, RepAppl(t) + 1, ap->ArityOfPE*sizeof(CELL) ); + memmove(out, RepAppl(t) + 1, ap->ArityOfPE * sizeof(CELL)); else out = RepAppl(t) + 1; } @@ -1022,12 +1012,12 @@ std::stringstream s; void YAPEngine::reSet() { /* ignore flags for now */ - if (B && B->cp_b && B->cp_ap != NOCODE ) - YAP_LeaveGoal(false, &q); + if (B && B->cp_b && B->cp_ap != NOCODE) + YAP_LeaveGoal(false, &q); LOCAL_ActiveError->errorNo = YAP_NO_ERROR; if (LOCAL_CommittedError) { LOCAL_CommittedError->errorNo = YAP_NO_ERROR; - free(LOCAL_CommittedError ); + free(LOCAL_CommittedError); LOCAL_CommittedError = NULL; } } diff --git a/CXX/yapi.hh b/CXX/yapi.hh index 8c122da2f..ba6ec0f16 100644 --- a/CXX/yapi.hh +++ b/CXX/yapi.hh @@ -106,6 +106,7 @@ X_API extern void YAP_UserBackCutCPredicate(const char *name, X_API extern YAP_Term YAP_ReadBuffer(const char *s, YAP_Term *tp); +extern YAP_Term YAP_MkcharPTerm(char *s); } diff --git a/CXX/yapq.hh b/CXX/yapq.hh index 662cf50e5..112fff187 100644 --- a/CXX/yapq.hh +++ b/CXX/yapq.hh @@ -178,6 +178,7 @@ public: // const std::string *s = new std::string("startup.yss"); Embedded = true; install = false; + Yap_InitDefaults(this, nullptr, 0, nullptr); #if YAP_PYTHON Embedded = true; diff --git a/CXX/yapt.hh b/CXX/yapt.hh index 21e66bde4..f07505234 100644 --- a/CXX/yapt.hh +++ b/CXX/yapt.hh @@ -27,6 +27,13 @@ class YAPError; +extern "C" { + +X_API extern Term YAP_MkCharPTerm( char *n); + + +} + /** * @brief Generic Prolog Term */ @@ -39,7 +46,7 @@ class X_API YAPTerm { friend class YAPApplTerm; friend class YAPListTerm; -protected: + protected: yhandle_t t; /// handle to term, equivalent to term_t public: @@ -110,7 +117,7 @@ public: /// numbervars ( int start, bool process=false ) intptr_t numberVars(intptr_t start, bool skip_singletons = false); inline Term term() { - return gt(); + return Deref(gt()); } /// from YAPTerm to Term (internal YAP representation) YAPTerm arg(int i) { BACKUP_MACHINE_REGS(); @@ -216,19 +223,15 @@ public: /// return a string with a textual representation of the term virtual const char *text() { CACHE_REGS - encoding_t enc = LOCAL_encoding; char *os; BACKUP_MACHINE_REGS(); - if (!(os = Yap_TermToBuffer(Yap_GetFromSlot(t), enc, Handle_vars_f))) { + if (!(os = Yap_TermToBuffer(Yap_GetFromSlot(t), Handle_vars_f))) { RECOVER_MACHINE_REGS(); return 0; } RECOVER_MACHINE_REGS(); - size_t length = strlen(os); - char *sm = (char *)malloc(length + 1); - strcpy(sm, os); - return sm; + return os; }; /// return a handle to the term @@ -315,12 +318,18 @@ public: RECOVER_MACHINE_REGS(); return tf; }; - void putArg(int i, YAPTerm t) { - BACKUP_MACHINE_REGS(); - Term t0 = gt(); - RepAppl(t0)[i] = t.term(); - RECOVER_MACHINE_REGS(); - }; + void putArg(int i, Term targ) { + //BACKUP_MACHINE_REGS(); + Term t0 = gt(); + RepAppl(t0)[i] = Deref(targ); + //RECOVER_MACHINE_REGS(); + }; + void putArg(int i, YAPTerm t) { + //BACKUP_MACHINE_REGS(); + Term t0 = gt(); + RepAppl(t0)[i] = t.term(); + //RECOVER_MACHINE_REGS(); + }; virtual bool isVar() { return false; } /// type check for unbound virtual bool isAtom() { return false; } /// type check for atom virtual bool isInteger() { return false; } /// type check for integer diff --git a/H/TermExt.h b/H/TermExt.h index f0975b063..cd2487948 100755 --- a/H/TermExt.h +++ b/H/TermExt.h @@ -288,6 +288,8 @@ INLINE_ONLY bool IsLongIntTerm(Term t) { /* extern Functor FunctorString; */ + + #define MkStringTerm(i) __MkStringTerm((i)PASS_REGS) INLINE_ONLY Term __MkStringTerm(const char *s USES_REGS); @@ -336,6 +338,31 @@ __MkUStringTerm(const unsigned char *s USES_REGS) { return t; } +#define MkCharPTerm(i) __MkCharPTerm((i)PASS_REGS) + +INLINE_ONLY Term __MkCharPTerm(char *s USES_REGS); + +INLINE_ONLY Term __MkCharPTerm(char *s USES_REGS) { + Term t = AbsAppl(HR); + size_t sz; + if (s[0] == '\0') { + sz = sizeof(CELL); + HR[0] = (CELL)FunctorString; + HR[1] = (CELL)sz; + HR[2] = 0; + } else { + sz = ALIGN_BY_TYPE(strlen((char *)s) + 1, CELL); + HR[0] = (CELL)FunctorString; + HR[1] = (CELL)sz; + strcpy((char *)(HR + 2), (const char *)s); + } + HR[2 + sz] = EndSpecials; + HR += 3 + sz; + return t; +} + + + INLINE_ONLY const unsigned char *UStringOfTerm(Term t); INLINE_ONLY const unsigned char *UStringOfTerm(Term t) { diff --git a/H/YapFlags.h b/H/YapFlags.h index 0207fd91b..ffadb6d5b 100644 --- a/H/YapFlags.h +++ b/H/YapFlags.h @@ -144,12 +144,12 @@ static Term synerr(Term inp) { return inp; if (IsAtomTerm(inp)) { - Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, inp, + Yap_ThrowError(DOMAIN_ERROR_OUT_OF_RANGE, inp, "set_prolog_flag in {dec10,error,fail,quiet}"); return TermZERO; } - Yap_Error(TYPE_ERROR_ATOM, inp, - "set_prolog_flag in {dec10,error,fail,quiet}"); + Yap_ThrowError(TYPE_ERROR_ATOM, inp, + "syntax_error flag must be atom"); return TermZERO; } diff --git a/H/YapGFlagInfo.h b/H/YapGFlagInfo.h index 1997267e8..8a35204b3 100644 --- a/H/YapGFlagInfo.h +++ b/H/YapGFlagInfo.h @@ -56,29 +56,26 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 ~~~ */ - - YAP_FLAG(ANSWER_FORMAT_FLAG, "answer_format", true, isatom, "~p", NULL), /**< how to present answers, default is `~p`. */ #if __ANDROID__ YAP_FLAG(ANDROID_FLAG, "android", false, booleanFlag, "true", NULL), /**< - read-only boolean, a machine running an Google's Android version of the Linux Operating System */ + read-only boolean, a machine running an Google's Android version of the + Linux Operating System */ #endif - #if __APPLE__ YAP_FLAG(APPLE_FLAG, "apple", false, booleanFlag, "true", NULL), /**< read-only boolean, a machine running an Apple Operating System */ #endif YAP_FLAG(ARCH_FLAG, "arch", false, isatom, YAP_ARCH, NULL), /**< read-only atom, it describes the ISA used in this version of YAP. - Available from YAP_AEH. + Available from YAP_ARCH. */ - YAP_FLAG(ARGV_FLAG, "argv", false, argv, "@boot", NULL), YAP_FLAG(ARITHMETIC_EXCEPTIONS_FLAG, "arithmetic_exceptions", true, booleanFlag, "true", NULL), - /**< `arithmetic_exceptions` + /**< Read-write flag telling whether arithmetic exceptions generate Prolog exceptions. If enabled: @@ -98,8 +95,8 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 It is `true` by default, but it is disabled by packages like CLP(BN) and ProbLog. */ - YAP_FLAG(BACK_QUOTES_FLAG, "back_quotes", true, isatom, "true", NULL), - /**> + YAP_FLAG(BACK_QUOTES_FLAG, "back_quotes", true, isatom, "true", bqs), + /**< If _Value_ is unbound, tell whether a back quoted list of characters token is converted to a list of atoms, `chars`, to a list of integers, `codes`, or to a single atom, `atom`. If _Value_ is bound, set to @@ -132,20 +129,22 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 Writable flag telling whether a character escapes are enabled, `true`, or disabled, `false`. The default value for this flag is `true`. */ - YAP_FLAG(COLON_SETS_CALLING_CONTEXT_FLAG, "colon_sets_calling_context", true, booleanFlag, "true", NULL), + YAP_FLAG(COLON_SETS_CALLING_CONTEXT_FLAG, "colon_sets_calling_context", + true, booleanFlag, "true", NULL), /**< `compiled_at ` - Read-only flag that gives the time when the main YAP binary was compiled. It - is obtained staight from the __TIME__ macro, as defined in the C99. - */ YAP_FLAG(COMPILED_AT_FLAG, "compiled_at", false, isatom, YAP_COMPILED_AT, + Read-only flag that gives the time when the main YAP binary was compiled. + It is obtained staight from the __TIME__ macro, as defined in the C99. + */ + YAP_FLAG(COMPILED_AT_FLAG, "compiled_at", false, isatom, YAP_COMPILED_AT, NULL), YAP_FLAG(DEBUG_FLAG, "debug", true, booleanFlag, "false", NULL), - /**< + /**< - If _Value_ is unbound, tell whether debugging is `true` or - `false`. If _Value_ is bound to `true` enable debugging, and if - it is bound to `false` disable debugging. - */ + If _Value_ is unbound, tell whether debugging is `true` or + `false`. If _Value_ is bound to `true` enable debugging, and if + it is bound to `false` disable debugging. +*/ YAP_FLAG(DEBUG_INFO_FLAG, "debug_info", true, booleanFlag, "true", NULL), YAP_FLAG(DEBUG_ON_ERROR_FLAG, "debug_on_error", true, booleanFlag, "true", NULL), @@ -159,6 +158,15 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 NULL), YAP_FLAG(DEBUGGER_SHOW_CONTEXT_FLAG, "debugger_show_context", true, booleanFlag, "false", NULL), + YAP_FLAG(DEFAULT_PARENT_MODULE_FLAG, "default_parent_module", true, isatom, + "user", NULL), + /**< + * A module to be inherited by all other modules. Default is user that + * reexports prolog. + * + * Set it to `prolog` for SICStus Prolog like resolution, to `user` for + * SWI-like. + */ YAP_FLAG(DIALECT_FLAG, "dialect", false, ro, "yap", NULL), /**< @@ -180,7 +188,7 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 booleanFlag, "false", NULL), /**< If `off` (default) consider the character `$` a control character, if - `on` consider `$` a lower case character. +vxu `on` consider `$` a lower case character. */ YAP_FLAG(DOUBLE_QUOTES_FLAG, "double_quotes", true, isatom, "codes", dqs), /**< iso @@ -269,11 +277,11 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 */ YAP_FLAG(INDEX_SUB_TERM_SEARCH_DEPTH_FLAG, "index_sub_term_search_depth", true, nat, "0", NULL), - /**< `Index_sub_term_search_depth ` + /**< `Index_sub_term_search_depth ` - Maximum bound on searching sub-terms for indexing, if `0` (default) no - bound. - */ + Maximum bound on searching sub-terms for indexing, if `0` (default) no + bound. +*/ YAP_FLAG(INFORMATIONAL_MESSAGES_FLAG, "informational_messages", true, isatom, "normal", NULL), /**< `informational_messages ` @@ -291,6 +299,8 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 value `toward_zero` for the current version of YAP. */ YAP_FLAG(ISO_FLAG, "iso", true, booleanFlag, "false", NULL), + YAP_FLAG(JUPYTER_FLAG, "jupyter", false, booleanFlag, "true", NULL), /**< + read-only boolean, a machine running Jupyter */ YAP_FLAG(LANGUAGE_FLAG, "language", true, isatom, "yap", NULL), /**< `language ` @@ -316,7 +326,7 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 Read-only flag telling the maximum arity of a functor. Takes the value `unbounded` for the current version of YAP. */ - YAP_FLAG(MAX_TAGGED_INTEGER_FLAG, "max_tagged_integer", false, at2n, + YAP_FLAG(MAX_TAGGED_INTEGER_FLAG, "max_tagged_integer", false, at2n, "INT_MAX", NULL), YAP_FLAG(MAX_THREADS_FLAG, "max_threads", false, at2n, "MAX_THREADS", NULL), YAP_FLAG(MAX_WORKERS_FLAG, "max_workers", false, at2n, "MAX_WORKERS", NULL), @@ -342,15 +352,14 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 providing access to shared libraries (`.so` files) or to dynamic link libraries (`.DLL` files). */ - /**< `module_independent_operators ` + /**< `module_independent_operators ` - If `true` an operator declaration will be valid for every module in the - program. This is for compatibility with old software that - might expect module-independent operators. - */ - YAP_FLAG(MODULE_INDEPENDENT_OPERATORS_FLAG, - "module_independent_operators", true, booleanFlag, - "false", NULL), + If `true` an operator declaration will be valid for every module in the + program. This is for compatibility with old software that + might expect module-independent operators. +*/ + YAP_FLAG(MODULE_INDEPENDENT_OPERATORS_FLAG, "module_independent_operators", + true, booleanFlag, "false", NULL), YAP_FLAG(OPTIMISE_FLAG, "optimise", true, booleanFlag, "false", NULL), YAP_FLAG(OS_ARGV_FLAG, "os_argv", false, os_argv, "@boot", NULL), @@ -366,14 +375,14 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 */ YAP_FLAG(PROMPT_ALTERNATIVES_ON_FLAG, "prompt_alternatives_on", true, isatom, "determinism", NULL), - /**< `prompt_alternatives_on(atom, - changeable) ` + /**< `prompt_alternatives_on(atom, + changeable) ` - SWI-Compatible option, determines prompting for alternatives in the Prolog - toplevel. Default is groundness, YAP prompts for alternatives if - and only if the query contains variables. The alternative, default in - SWI-Prolog is determinism which implies the system prompts for - alternatives if the goal succeeded while leaving choicepoints. */ + SWI-Compatible option, determines prompting for alternatives in the Prolog + toplevel. Default is groundness, YAP prompts for alternatives if + and only if the query contains variables. The alternative, default in + SWI-Prolog is determinism which implies the system prompts for + alternatives if the goal succeeded while leaving choicepoints. */ YAP_FLAG(QUASI_QUOTATIONS_FLAG, "quasi_quotations", true, booleanFlag, "true", NULL), YAP_FLAG(READLINE_FLAG, "readline", true, booleanFlag, "false", @@ -383,6 +392,15 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 enable the use of the readline library for console interactions, true by default if readline was found. */ + YAP_FLAG(REDEFINE_WARNINGS_FLAG, "redefine_warnings", true, booleanFlag, + "true", NULL), /**< + +If _Value_ is unbound, tell whether warnings for procedures defined +in several different files are `on` or +`off`. If _Value_ is bound to `on` enable these warnings, +and if it is bound to `off` disable them. The default for YAP is +`off`, unless we are in `sicstus` or `iso` mode. +*/ YAP_FLAG(REPORT_ERROR_FLAG, "report_error", true, booleanFlag, "true", NULL), YAP_FLAG(RESOURCE_DATABASE_FLAG, "resource_database", false, isatom, @@ -418,6 +436,15 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 /**< `single_quoted text is usuallly interpreted as atoms. This flagTerm allows other inerpretations such as strings_contains_strings */ + YAP_FLAG(SINGLE_VAR_WARNINGS_FLAG, "single_var_warnings", true, booleanFlag, + "true", NULL), /**< + If `true` (default `true`) YAP checks for singleton + variables when loading files. A singleton variable is a + variable that appears ony once in a clause. The name + must start with a capital letter, variables whose name + starts with underscore are never considered singleton. + + */ YAP_FLAG(SIGNALS_FLAG, "signals", true, booleanFlag, "true", NULL), /**< `signals` @@ -476,10 +503,7 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 */ YAP_FLAG(THREADS_FLAG, "threads", false, ro, "MAX_THREADS", NULL), YAP_FLAG(TIMEZONE_FLAG, "timezone", false, ro, "18000", NULL), - YAP_FLAG(TOPLEVEL_PRINT_ANON_FLAG, "toplevel_print_anon", true, booleanFlag, - "true", NULL), - YAP_FLAG(TOPLEVEL_HOOK_FLAG, "toplevel_hook", true, - booleanFlag, "true", + YAP_FLAG(TOPLEVEL_HOOK_FLAG, "toplevel_hook", true, booleanFlag, "true", NULL), /**< `toplevel_hook ` @@ -489,6 +513,8 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 backtracked into. */ + YAP_FLAG(TOPLEVEL_PRINT_ANON_FLAG, "toplevel_print_anon", true, booleanFlag, + "true", NULL), YAP_FLAG(TOPLEVEL_PRINT_OPTIONS_FLAG, "toplevel_print_options", true, list_option, "[quoted(true),numbervars(true),portrayed(true)]", NULL), @@ -521,9 +547,9 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 are `silent`, `warning` and `error`. The first two create the flag on-the-fly, with `warning` printing a message. The value `error` is consistent with ISO: it raises an existence error and does not create the - flag. See also `create_prolog_flag/3`. The default is`error`, and developers - are encouraged to use `create_prolog_flag/3` to create flags for their - library. + flag. See also `create_prolog_flag/3`. The default is`error`, and + developers are encouraged to use `create_prolog_flag/3` to create flags for + their library. */ YAP_FLAG(UNKNOWN_FLAG, "unknown", true, isatom, "error", Yap_unknown), /**< `unknown is iso` diff --git a/H/YapLFlagInfo.h b/H/YapLFlagInfo.h index 24c16cc53..22cce7aa7 100644 --- a/H/YapLFlagInfo.h +++ b/H/YapLFlagInfo.h @@ -1,21 +1,19 @@ /************************************************************************* -* * -* YAP Prolog * -* * -* Yap Prolog was developed at NCCUP - Universidade do Porto * -* * -* Copyright L.Damas, V.S.Costa and Universidade do Porto 2015- * -* * -************************************************************************** -* * -* File: YapLFlagInfo.h * -* Last rev: * -* mods: * -* comments: local flag enumeration. * -* * -*************************************************************************/ + * * + * YAP Prolog * + * * + * Yap Prolog was developed at NCCUP - Universidade do Porto * + * * + * Copyright L.Damas, V.S.Costa and Universidade do Porto 2015- * + * * + ************************************************************************** + * * + * File: YapLFlagInfo.h * Last rev: + ** mods: * comments: local flag enumeration. * + * * + *************************************************************************/ /** @file YapLFlagInfo.h @@ -30,74 +28,75 @@ START_LOCAL_FLAGS - /** + `autoload`: set the system to look for undefined procedures */ -YAP_FLAG( AUTOLOAD_FLAG, "autoload", true, booleanFlag, "false" , NULL ), -/** + `read-only flag, that tells if Prolog is in an inner top-level */ -YAP_FLAG( BREAK_LEVEL_FLAG, "break_level", true, nat, "0" , NULL ), -YAP_FLAG( CALL_COUNTING_FLAG, "call_counting", true, booleanFlag, "true" , NULL ), /** + `call_counting` +/** + `autoload`: set the system to look for undefined procedures */ +YAP_FLAG(AUTOLOAD_FLAG, "autoload", true, booleanFlag, "false", NULL), + /** + `read-only flag, that tells if Prolog is in an inner top-level */ + YAP_FLAG(BREAK_LEVEL_FLAG, "break_level", true, nat, "0", NULL), + YAP_FLAG(CALL_COUNTING_FLAG, "call_counting", true, booleanFlag, "true", + NULL), /** + `call_counting` - Predicates compiled with this flag set maintain a counter on the numbers of proceduree calls and of retries. These counters are decreasing counters, and they can be used as timers. Three counters are available: + Predicates compiled with this flag set maintain a counter + on the numbers of proceduree calls and of retries. These counters + are decreasing counters, and they can be used as timers. Three + counters are available: - calls: number of predicate calls since execution started or since system was reset; - retries: number of retries for predicates called since execution started or since counters were reset; - calls_and_retries: count both on predicate calls and retries. - These counters can be used to find out how many calls a certain goal takes to execute. They can also be force the computatiom yp - stopping. + calls: number of predicate calls since execution started or + since system was reset; retries: number of retries for predicates + called since execution started or since counters were reset; + calls_and_retries: count both on predicate calls and + retries. These counters can be used to find out how many calls a + certain goal takes to execute. They can also be force the + computatiom yp stopping. - If `on` `fileerrors` is `on`, if `off` (default) - `fileerrors` is disabled. - */ -YAP_FLAG( ENCODING_FLAG, "encoding", true, isatom, "utf-8" , getenc ), -YAP_FLAG( FILEERRORS_FLAG, "fileerrors", true, booleanFlag, "true" , NULL ), /** + `fileerrors` + If `on` `fileerrors` is `on`, if `off` (default) + `fileerrors` is disabled. + */ + YAP_FLAG(ENCODING_FLAG, "encoding", true, isatom, "utf-8", getenc), + YAP_FLAG(FILEERRORS_FLAG, "fileerrors", true, booleanFlag, "true", + NULL), /** + `fileerrors` - If `on` `fileerrors` is `on`, if `off` (default) - `fileerrors` is disabled. - */ -YAP_FLAG( LANGUAGE_MODE_FLAG, "language_mode", true, isatom, "yap" , NULL ), /** + `language_mode` + If `on` `fileerrors` is `on`, if `off` (default) + `fileerrors` is disabled. + */ + YAP_FLAG(LANGUAGE_MODE_FLAG, "language_mode", true, isatom, "yap", + NULL), /** + `language_mode` - wweter native mode or trying to emulate a different Prolog. - */ -YAP_FLAG( REDEFINE_WARNINGS_FLAG, "redefine_warnings", true, booleanFlag, "true" , NULL ), /** + `redefine_warnings ` + wweter native mode or trying to emulate a different Prolog. + */ + YAP_FLAG(STACK_DUMP_ON_ERROR_FLAG, "stack_dump_on_error", true, booleanFlag, + "true", NULL), /** + `stack_dump_on_error ` - If _Value_ is unbound, tell whether warnings for procedures defined -in several different files are `on` or -`off`. If _Value_ is bound to `on` enable these warnings, -and if it is bound to `off` disable them. The default for YAP is -`off`, unless we are in `sicstus` or `iso` mode. - */ -YAP_FLAG( SINGLE_VAR_WARNINGS_FLAG, "single_var_warnings", true, booleanFlag, "true" , NULL ), /** + `single_var_warnings` - If `true` (default `true`) YAP checks for singleton variables when loading files. A singleton variable is a variable that appears ony once in a clause. The name must start with a capital letter, variables whose name starts with underscore are never considered singleton. - - */ -YAP_FLAG( STACK_DUMP_ON_ERROR_FLAG, "stack_dump_on_error", true, booleanFlag, "false" , NULL ), /** + `stack_dump_on_error ` - - If `true` show a stack dump when YAP finds an error. The default is +If `true` show a stack dump when YAP finds an error. The default is `off`. - */ -YAP_FLAG( STREAM_TYPE_CHECK_FLAG, "stream_type_check", true, isatom, "loose" , NULL ), -YAP_FLAG( SYNTAX_ERRORS_FLAG, "syntax_errors", true, synerr, "error" , NULL ), /** + `syntax_errors` +*/ + YAP_FLAG(STREAM_TYPE_CHECK_FLAG, "stream_type_check", true, isatom, "loose", + NULL), + YAP_FLAG(SYNTAX_ERRORS_FLAG, "syntax_errors", true, synerr, "error", + NULL), /** + `syntax_errors` - Control action to be taken after syntax errors while executing read/1, +Control action to be taken after syntax errors while executing read/1, `read/2`, or `read_term/3`: - + `dec10` ++ `dec10` Report the syntax error and retry reading the term. - + `fail` ++ `fail` Report the syntax error and fail. - + `error` ++ `error` Report the syntax error and generate an error (default). - + `quiet` ++ `quiet` Just fail - */ -YAP_FLAG( TYPEIN_MODULE_FLAG, "typein_module", true, isatom, "user" , typein ), /** + `typein_module ` +*/ + YAP_FLAG(TYPEIN_MODULE_FLAG, "typein_module", true, isatom, "user", + typein), /** + `typein_module ` - If bound, set the current working or type-in module to the argument, +If bound, set the current working or type-in module to the argument, which must be an atom. If unbound, unify the argument with the current working module. - */ - YAP_FLAG( USER_ERROR_FLAG, "user_error", true, stream, "user_error" , set_error_stream ), /** + `user_error1` +*/ + YAP_FLAG(USER_ERROR_FLAG, "user_error", true, stream, "user_error", + set_error_stream), /** + `user_error1` - If the second argument is bound to a stream, set user_error to +If the second argument is bound to a stream, set user_error to this stream. If the second argument is unbound, unify the argument with the current user_error stream. By default, the user_error stream is set to a stream @@ -105,30 +104,32 @@ corresponding to the Unix `stderr` stream. The next example shows how to use this flag: ~~~{.prolog} - ?- open( '/dev/null', append, Error, - [alias(mauri_tripa)] ). +?- open( '/dev/null', append, Error, +[alias(mauri_tripa)] ). - Error = '$stream'(3) ? ; +Error = '$stream'(3) ? ; - no - ?- set_prolog_flag(user_error, mauri_tripa). +no +?- set_prolog_flag(user_error, mauri_tripa). - close(mauri_tripa). +close(mauri_tripa). - yes - ?- +yes +?- ~~~ - We execute three commands. First, we open a stream in write mode and +We execute three commands. First, we open a stream in write mode and give it an alias, in this case `mauri_tripa`. Next, we set user_error to the stream via the alias. Note that after we did so prompts from the system were redirected to the stream `mauri_tripa`. Last, we close the stream. At this point, YAP automatically redirects the user_error alias to the original `stderr`. - */ -YAP_FLAG( USER_INPUT_FLAG, "user_input", true, stream, "user_input" , set_input_stream ), - YAP_FLAG( USER_OUTPUT_FLAG, "user_output", true, stream, "user_output" , set_output_stream ), +*/ + YAP_FLAG(USER_INPUT_FLAG, "user_input", true, stream, "user_input", + set_input_stream), + YAP_FLAG(USER_OUTPUT_FLAG, "user_output", true, stream, "user_output", + set_output_stream), -END_LOCAL_FLAGS + END_LOCAL_FLAGS -/// @} + /// @} diff --git a/H/YapText.h b/H/YapText.h index d5a1ed0ae..953e6a4b8 100644 --- a/H/YapText.h +++ b/H/YapText.h @@ -543,6 +543,22 @@ static inline Term Yap_AtomToListOfCodes(Term t0 USES_REGS) { return out.val.t; } +static inline Term Yap_AtomSWIToListOfCodes(Term t0 USES_REGS) { + seq_tv_t inp, out; + + inp.val.t = t0; + inp.type = YAP_STRING_ATOM | YAP_STRING_STRING | YAP_STRING_INT | + YAP_STRING_FLOAT | YAP_STRING_BIG | YAP_STRING_ATOMS_CODES |YAP_STRING_ATOMS_CODES |YAP_STRING_ATOMS_CODES | + YAP_STRING_TERM; + out.val.uc = NULL; + out.type = YAP_STRING_CODES; + + if (!Yap_CVT_Text(&inp, &out PASS_REGS)) + return 0L; + return out.val.t; +} + + static inline Term Yap_AtomToNumber(Term t0 USES_REGS) { seq_tv_t inp, out; inp.val.t = t0; diff --git a/H/Yapproto.h b/H/Yapproto.h index 93f5af1fe..89c85cc56 100755 --- a/H/Yapproto.h +++ b/H/Yapproto.h @@ -35,6 +35,7 @@ extern int Yap_HasOp(Atom); extern struct operator_entry * Yap_GetOpPropForAModuleHavingALock(struct AtomEntryStruct *, Term); extern Atom Yap_LookupAtom(const char *); +extern Atom Yap_AtomInUse(const char *atom); extern Atom Yap_ULookupAtom(const unsigned char *); extern Atom Yap_LookupAtomWithLength(const char *, size_t); extern Atom Yap_FullLookupAtom(const char *); @@ -309,7 +310,6 @@ extern void Yap_DebugPlWriteln(Term t); extern void Yap_DebugErrorPutc(int n); extern void Yap_DebugErrorPuts(const char *s); extern void Yap_DebugWriteIndicator(struct pred_entry *ap); -extern void Yap_PlWriteToStream(Term, int, int); extern void Yap_CloseReadline(void); /* depth_lim.c */ extern bool Yap_InitReadline(Term t); diff --git a/H/Yatom.h b/H/Yatom.h index 0b1906f7e..522bc507f 100755 --- a/H/Yatom.h +++ b/H/Yatom.h @@ -1298,7 +1298,7 @@ INLINE_ONLY bool IsFlagProperty(PropFlags flags) { /* Proto types */ -extern char *Yap_TermToBuffer(Term t, encoding_t encoding, int flags); +extern char *Yap_TermToBuffer(Term t, int flags); extern Term Yap_BufferToTerm(const char *s, Term opts); diff --git a/H/absmi.h b/H/absmi.h index ec215741e..2a3e9bacf 100755 --- a/H/absmi.h +++ b/H/absmi.h @@ -181,14 +181,14 @@ INLINE_ONLY void init_absmi_regs(REGSTORE *absmi_regs); INLINE_ONLY void init_absmi_regs(REGSTORE *absmi_regs) { CACHE_REGS - memcpy(absmi_regs, Yap_regp, sizeof(REGSTORE)); + memmove(absmi_regs, Yap_regp, sizeof(REGSTORE)); } INLINE_ONLY void restore_absmi_regs(REGSTORE *old_regs); INLINE_ONLY void restore_absmi_regs(REGSTORE *old_regs) { CACHE_REGS - memcpy(old_regs, Yap_regp, sizeof(REGSTORE)); + memmove(old_regs, Yap_regp, sizeof(REGSTORE)); #ifdef THREADS pthread_setspecific(Yap_yaamregs_key, (void *)old_regs); LOCAL_ThreadHandle.current_yaam_regs = old_regs; diff --git a/H/amijit.h b/H/amijit.h index e9244b7c3..39daff70e 100644 --- a/H/amijit.h +++ b/H/amijit.h @@ -95,7 +95,7 @@ typedef enum{ t_createLowerExpectIntrinsicPass, //Removes llvm.expect intrinsics and creates "block_weights" metadata t_createLowerInvokePass, //Converts invoke and unwind instructions to use sjlj exception handling mechanisms t_createLowerSwitchPass, //Converts SwitchInst instructions into a sequence of chained binary branch instructions - t_createMemCpyOptPass, //Performs optimizations related to eliminating memcpy calls and/or combining multiple stores into memset's + t_createMemCpyOptPass, //Performs optimizations related to eliminating memmove calls and/or combining multiple stores into memset's t_createMergeFunctionsPass, //Discovers identical functions and collapses them t_createObjCARCAPElimPass, //ObjC ARC autorelease pool elimination t_createObjCARCContractPass, //Late ObjC ARC cleanups diff --git a/H/clause.h b/H/clause.h index 12760351b..1b2d55903 100644 --- a/H/clause.h +++ b/H/clause.h @@ -24,7 +24,7 @@ /* consulting files */ typedef union CONSULT_OBJ { - const unsigned char *f_name; + Atom f_name; int mode; Prop p; UInt c; diff --git a/H/utarray.h b/H/utarray.h index 0c1e59b5b..415652439 100644 --- a/H/utarray.h +++ b/H/utarray.h @@ -95,7 +95,7 @@ typedef struct { #define utarray_push_back(a,p) do { \ utarray_reserve(a,1); \ if ((a)->icd.copy) { (a)->icd.copy( _utarray_eltptr(a,(a)->i++), p); } \ - else { memcpy(_utarray_eltptr(a,(a)->i++), p, (a)->icd.sz); }; \ + else { memmove(_utarray_eltptr(a,(a)->i++), p, (a)->icd.sz); }; \ } while(0) #define utarray_pop_back(a) do { \ @@ -123,7 +123,7 @@ typedef struct { ((a)->i - (j))*((a)->icd.sz)); \ } \ if ((a)->icd.copy) { (a)->icd.copy( _utarray_eltptr(a,j), p); } \ - else { memcpy(_utarray_eltptr(a,j), p, (a)->icd.sz); }; \ + else { memmove(_utarray_eltptr(a,j), p, (a)->icd.sz); }; \ (a)->i++; \ } while(0) @@ -142,7 +142,7 @@ typedef struct { (a)->icd.copy(_utarray_eltptr(a,j+_ut_i), _utarray_eltptr(w,_ut_i)); \ } \ } else { \ - memcpy(_utarray_eltptr(a,j), _utarray_eltptr(w,0), \ + memmove(_utarray_eltptr(a,j), _utarray_eltptr(w,0), \ utarray_len(w)*((a)->icd.sz)); \ } \ (a)->i += utarray_len(w); \ diff --git a/JIT/JIT_interface.cpp b/JIT/JIT_interface.cpp index bf5b5cf58..9a684512e 100644 --- a/JIT/JIT_interface.cpp +++ b/JIT/JIT_interface.cpp @@ -95,7 +95,7 @@ typedef enum{ t_createLowerExpectIntrinsicPass, //Removes llvm.expect intrinsics and creates "block_weights" metadata t_createLowerInvokePass, //Converts invoke and unwind instructions to use sjlj exception handling mechanisms t_createLowerSwitchPass, //Converts SwitchInst instructions into a sequence of chained binary branch instructions - t_createMemCpyOptPass, //Performs optimizations related to eliminating memcpy calls and/or combining multiple stores into memset's + t_createMemCpyOptPass, //Performs optimizations related to eliminating memmove calls and/or combining multiple stores into memset's t_createMergeFunctionsPass, //Discovers identical functions and collapses them t_createObjCARCAPElimPass, //ObjC ARC autorelease pool elimination t_createObjCARCContractPass, //Late ObjC ARC cleanups diff --git a/OPTYap/or.copy_engine.c b/OPTYap/or.copy_engine.c index a45a68d8a..443aeddca 100644 --- a/OPTYap/or.copy_engine.c +++ b/OPTYap/or.copy_engine.c @@ -66,29 +66,29 @@ static void share_private_nodes(int worker_q); #endif #define P_COPY_GLOBAL_TO(Q) \ - memcpy((void *) (worker_offset(Q) + REMOTE_start_global_copy(Q)), \ + memmove((void *) (worker_offset(Q) + REMOTE_start_global_copy(Q)), \ (void *) REMOTE_start_global_copy(Q), \ (size_t) (REMOTE_end_global_copy(Q) - REMOTE_start_global_copy(Q))) #define Q_COPY_GLOBAL_FROM(P) \ - memcpy((void *) LOCAL_start_global_copy, \ + memmove((void *) LOCAL_start_global_copy, \ (void *) (worker_offset(P) + LOCAL_start_global_copy), \ (size_t) (LOCAL_end_global_copy - LOCAL_start_global_copy)) #define P_COPY_LOCAL_TO(Q) \ - memcpy((void *) (worker_offset(Q) + REMOTE_start_local_copy(Q)), \ + memmove((void *) (worker_offset(Q) + REMOTE_start_local_copy(Q)), \ (void *) REMOTE_start_local_copy(Q), \ (size_t) (REMOTE_end_local_copy(Q) - REMOTE_start_local_copy(Q))) #define Q_COPY_LOCAL_FROM(P) \ - memcpy((void *) LOCAL_start_local_copy, \ + memmove((void *) LOCAL_start_local_copy, \ (void *) (worker_offset(P) + LOCAL_start_local_copy), \ (size_t) (LOCAL_end_local_copy - LOCAL_start_local_copy)) #define P_COPY_TRAIL_TO(Q) \ - memcpy((void *) (worker_offset(Q) + REMOTE_start_trail_copy(Q)), \ + memmove((void *) (worker_offset(Q) + REMOTE_start_trail_copy(Q)), \ (void *) REMOTE_start_trail_copy(Q), \ (size_t) (REMOTE_end_trail_copy(Q) - REMOTE_start_trail_copy(Q))) #define Q_COPY_TRAIL_FROM(P) \ - memcpy((void *) LOCAL_start_trail_copy, \ + memmove((void *) LOCAL_start_trail_copy, \ (void *) (worker_offset(P) + LOCAL_start_trail_copy), \ (size_t) (LOCAL_end_trail_copy - LOCAL_start_trail_copy)) diff --git a/OPTYap/tab.completion.c b/OPTYap/tab.completion.c index c8ad626dd..5dc16a557 100644 --- a/OPTYap/tab.completion.c +++ b/OPTYap/tab.completion.c @@ -409,13 +409,13 @@ void resume_suspension_frame(susp_fr_ptr resume_fr, or_fr_ptr top_or_fr) { sg_fr_ptr sg_frame; /* copy suspended stacks */ - memcpy(SuspFr_global_reg(resume_fr), + memmove(SuspFr_global_reg(resume_fr), SuspFr_global_start(resume_fr), SuspFr_global_size(resume_fr)); - memcpy(SuspFr_local_reg(resume_fr), + memmove(SuspFr_local_reg(resume_fr), SuspFr_local_start(resume_fr), SuspFr_local_size(resume_fr)); - memcpy(SuspFr_trail_reg(resume_fr), + memmove(SuspFr_trail_reg(resume_fr), SuspFr_trail_start(resume_fr), SuspFr_trail_size(resume_fr)); diff --git a/OPTYap/tab.macros.h b/OPTYap/tab.macros.h index 290246e6d..c8ba70d0b 100644 --- a/OPTYap/tab.macros.h +++ b/OPTYap/tab.macros.h @@ -574,9 +574,9 @@ typedef enum { SuspFr_global_size(SUSP_FR) = H_SIZE; \ SuspFr_local_size(SUSP_FR) = B_SIZE; \ SuspFr_trail_size(SUSP_FR) = TR_SIZE; \ - memcpy(SuspFr_global_start(SUSP_FR), SuspFr_global_reg(SUSP_FR), H_SIZE); \ - memcpy(SuspFr_local_start(SUSP_FR), SuspFr_local_reg(SUSP_FR), B_SIZE); \ - memcpy(SuspFr_trail_start(SUSP_FR), SuspFr_trail_reg(SUSP_FR), TR_SIZE) + memmove(SuspFr_global_start(SUSP_FR), SuspFr_global_reg(SUSP_FR), H_SIZE); \ + memmove(SuspFr_local_start(SUSP_FR), SuspFr_local_reg(SUSP_FR), B_SIZE); \ + memmove(SuspFr_trail_start(SUSP_FR), SuspFr_trail_reg(SUSP_FR), TR_SIZE) #define new_subgoal_trie_node(NODE, ENTRY, CHILD, PARENT, NEXT) \ ALLOC_SUBGOAL_TRIE_NODE(NODE); \ diff --git a/OPTYap/tab.tries.c b/OPTYap/tab.tries.c index 9f21e184d..53e19d39a 100644 --- a/OPTYap/tab.tries.c +++ b/OPTYap/tab.tries.c @@ -665,12 +665,12 @@ static void traverse_subgoal_trie(sg_node_ptr current_node, char *str, bucket = Hash_buckets(hash); last_bucket = bucket + Hash_num_buckets(hash); current_arity = (int *)malloc(sizeof(int) * (arity[0] + 1)); - memcpy(current_arity, arity, sizeof(int) * (arity[0] + 1)); + memmove(current_arity, arity, sizeof(int) * (arity[0] + 1)); do { if (*bucket) { traverse_subgoal_trie(*bucket, str, str_index, arity, mode, TRAVERSE_POSITION_FIRST PASS_REGS); - memcpy(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); + memmove(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); #ifdef TRIE_COMPACT_PAIRS if (arity[arity[0]] == -2 && str[str_index - 1] != '[') str[str_index - 1] = ','; @@ -687,7 +687,7 @@ static void traverse_subgoal_trie(sg_node_ptr current_node, char *str, /* save current state if first sibling node */ if (position == TRAVERSE_POSITION_FIRST) { current_arity = (int *)malloc(sizeof(int) * (arity[0] + 1)); - memcpy(current_arity, arity, sizeof(int) * (arity[0] + 1)); + memmove(current_arity, arity, sizeof(int) * (arity[0] + 1)); current_str_index = str_index; current_mode = mode; } @@ -737,7 +737,7 @@ static void traverse_subgoal_trie(sg_node_ptr current_node, char *str, mode = current_mode; current_node = TrNode_next(current_node); while (current_node) { - memcpy(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); + memmove(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); #ifdef TRIE_COMPACT_PAIRS if (arity[arity[0]] == -2 && str[str_index - 1] != '[') str[str_index - 1] = ','; @@ -768,12 +768,12 @@ static void traverse_answer_trie(ans_node_ptr current_node, char *str, bucket = Hash_buckets(hash); last_bucket = bucket + Hash_num_buckets(hash); current_arity = (int *)malloc(sizeof(int) * (arity[0] + 1)); - memcpy(current_arity, arity, sizeof(int) * (arity[0] + 1)); + memmove(current_arity, arity, sizeof(int) * (arity[0] + 1)); do { if (*bucket) { traverse_answer_trie(*bucket, str, str_index, arity, var_index, mode, TRAVERSE_POSITION_FIRST PASS_REGS); - memcpy(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); + memmove(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); #ifdef TRIE_COMPACT_PAIRS if (arity[arity[0]] == -2 && str[str_index - 1] != '[') str[str_index - 1] = ','; @@ -790,7 +790,7 @@ static void traverse_answer_trie(ans_node_ptr current_node, char *str, /* save current state if first sibling node */ if (position == TRAVERSE_POSITION_FIRST) { current_arity = (int *)malloc(sizeof(int) * (arity[0] + 1)); - memcpy(current_arity, arity, sizeof(int) * (arity[0] + 1)); + memmove(current_arity, arity, sizeof(int) * (arity[0] + 1)); current_str_index = str_index; current_var_index = var_index; current_mode = mode; @@ -832,7 +832,7 @@ static void traverse_answer_trie(ans_node_ptr current_node, char *str, mode = current_mode; current_node = TrNode_next(current_node); while (current_node) { - memcpy(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); + memmove(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); #ifdef TRIE_COMPACT_PAIRS if (arity[arity[0]] == -2 && str[str_index - 1] != '[') str[str_index - 1] = ','; @@ -863,12 +863,12 @@ static void traverse_global_trie(gt_node_ptr current_node, char *str, bucket = Hash_buckets(hash); last_bucket = bucket + Hash_num_buckets(hash); current_arity = (int *)malloc(sizeof(int) * (arity[0] + 1)); - memcpy(current_arity, arity, sizeof(int) * (arity[0] + 1)); + memmove(current_arity, arity, sizeof(int) * (arity[0] + 1)); do { if (*bucket) { traverse_global_trie(*bucket, str, str_index, arity, mode, TRAVERSE_POSITION_FIRST PASS_REGS); - memcpy(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); + memmove(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); #ifdef TRIE_COMPACT_PAIRS if (arity[arity[0]] == -2 && str[str_index - 1] != '[') str[str_index - 1] = ','; @@ -885,7 +885,7 @@ static void traverse_global_trie(gt_node_ptr current_node, char *str, /* save current state if first sibling node */ if (position == TRAVERSE_POSITION_FIRST) { current_arity = (int *)malloc(sizeof(int) * (arity[0] + 1)); - memcpy(current_arity, arity, sizeof(int) * (arity[0] + 1)); + memmove(current_arity, arity, sizeof(int) * (arity[0] + 1)); current_str_index = str_index; current_mode = mode; } @@ -913,7 +913,7 @@ static void traverse_global_trie(gt_node_ptr current_node, char *str, mode = current_mode; current_node = TrNode_next(current_node); while (current_node) { - memcpy(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); + memmove(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); #ifdef TRIE_COMPACT_PAIRS if (arity[arity[0]] == -2 && str[str_index - 1] != '[') str[str_index - 1] = ','; @@ -1200,7 +1200,7 @@ sg_fr_ptr subgoal_search(yamop *preg, CELL **Yaddr) { #ifdef MODE_DIRECTED_TABLING if (subs_pos) { ALLOC_BLOCK(mode_directed, subs_pos * sizeof(int), int); - memcpy((void *)mode_directed, (void *)aux_mode_directed, + memmove((void *)mode_directed, (void *)aux_mode_directed, subs_pos * sizeof(int)); } else mode_directed = NULL; diff --git a/OPTYap/tab.tries.insts.h b/OPTYap/tab.tries.insts.h index 55ae5df44..8553fe50c 100644 --- a/OPTYap/tab.tries.insts.h +++ b/OPTYap/tab.tries.insts.h @@ -77,7 +77,7 @@ #define copy_aux_stack() \ { arity_t size = 3 + heap_arity + subs_arity + vars_arity; \ TOP_STACK -= size; \ - memcpy(TOP_STACK, aux_stack, size * sizeof(CELL *)); \ + memmove(TOP_STACK, aux_stack, size * sizeof(CELL *)); \ aux_stack = TOP_STACK; \ }/* macros 'store_trie_node', 'restore_trie_node' and 'pop_trie_node' ** ** do not include 'set_cut' because trie instructions are cut safe */ diff --git a/OPTYap/traced_tab.tries.insts.h b/OPTYap/traced_tab.tries.insts.h index 2c8ac324d..d873bbc18 100644 --- a/OPTYap/traced_tab.tries.insts.h +++ b/OPTYap/traced_tab.tries.insts.h @@ -77,7 +77,7 @@ #define copy_aux_stack() \ { int size = 3 + heap_arity + subs_arity + vars_arity; \ TOP_STACK -= size; \ - memcpy(TOP_STACK, aux_stack, size * sizeof(CELL *)); \ + memmove(TOP_STACK, aux_stack, size * sizeof(CELL *)); \ aux_stack = TOP_STACK; \ }/* macros 'store_trie_node', 'restore_trie_node' and 'pop_trie_node' ** ** do not include 'set_cut' because trie instructions are cut safe */ diff --git a/autoconf/config.h.in b/autoconf/config.h.in index e947b7598..63aaa0301 100644 --- a/autoconf/config.h.in +++ b/autoconf/config.h.in @@ -496,7 +496,7 @@ /* Define to 1 if you have the `mbsnrtowcs' function. */ #undef HAVE_MBSNRTOWCS -/* Define to 1 if you have the `memcpy' function. */ +/* Define to 1 if you have the `memmove' function. */ #undef HAVE_MEMCPY /* Define to 1 if you have the `memmove' function. */ diff --git a/autoconf/configure.in b/autoconf/configure.in index 90f79ab4f..525de3f88 100755 --- a/autoconf/configure.in +++ b/autoconf/configure.in @@ -1767,7 +1767,7 @@ AC_CHECK_FUNCS(localeconv localtime lstat mallinfo) AC_CHECK_FUNCS(mbscoll) AC_CHECK_FUNCS(mbscasecoll) AC_CHECK_FUNCS(mbsnrtowcs) -AC_CHECK_FUNCS(memcpy memmove mkstemp mktemp) +AC_CHECK_FUNCS(memmove memmove mkstemp mktemp) AC_CHECK_FUNCS(nanosleep mktime opendir) AC_CHECK_FUNCS(putenv rand random drand48) AC_CHECK_FUNCS(readlink realpath regexec) diff --git a/cmake/Config.cmake b/cmake/Config.cmake index 89331f891..094d3ce42 100644 --- a/cmake/Config.cmake +++ b/cmake/Config.cmake @@ -291,7 +291,7 @@ check_symbol_exists(mallinfo " malloc.h" HAVE_MALLINFO) check_function_exists(mbscoll HAVE_MBSCOLL) check_function_exists(mbscasecoll HAVE_MBSCASECOLL) check_function_exists(mbsnrtowcs HAVE_MBSNRTOWCS) -check_function_exists(memcpy HAVE_MEMCPY) +check_function_exists(memmove HAVE_MEMCPY) check_function_exists(memmove HAVE_MEMMOVE) check_function_exists(mkstemp HAVE_MKSTEMP) check_function_exists(mktemp HAVE_MKTEMP) diff --git a/cmake/FindLibR.cmake b/cmake/FindLibR.cmake index d6a05569d..1bdfe994e 100755 --- a/cmake/FindLibR.cmake +++ b/cmake/FindLibR.cmake @@ -1,7 +1,7 @@ # # FindLibR.cmake # -# Copyright (C) 2009-11 by RStudio, Inc. +# Copyright (C) 2009-18 by RStudio, Inc. # # This program is licensed to you under the terms of version 3 of the # GNU Affero General Public License. This program is distributed WITHOUT @@ -21,11 +21,24 @@ if(APPLE) find_library(LIBR_LIBRARIES R) - if(LIBR_LIBRARIES) + + if(LIBR_LIBRARIES MATCHES ".*\\.framework") set(LIBR_HOME "${LIBR_LIBRARIES}/Resources" CACHE PATH "R home directory") set(LIBR_INCLUDE_DIRS "${LIBR_HOME}/include" CACHE PATH "R include directory") set(LIBR_DOC_DIR "${LIBR_HOME}/doc" CACHE PATH "R doc directory") set(LIBR_EXECUTABLE "${LIBR_HOME}/R" CACHE PATH "R executable") + else() + get_filename_component(_LIBR_LIBRARIES "${LIBR_LIBRARIES}" REALPATH) + get_filename_component(_LIBR_LIBRARIES_DIR "${_LIBR_LIBRARIES}" PATH) + set(LIBR_EXECUTABLE "${_LIBR_LIBRARIES_DIR}/../bin/R") + execute_process( + COMMAND ${LIBR_EXECUTABLE} "--slave" "--vanilla" "-e" "cat(R.home())" + OUTPUT_VARIABLE LIBR_HOME + ) + set(LIBR_HOME ${LIBR_HOME} CACHE PATH "R home directory") + set(LIBR_INCLUDE_DIRS "${LIBR_HOME}/include" CACHE PATH "R include directory") + set(LIBR_DOC_DIR "${LIBR_HOME}/doc" CACHE PATH "R doc directory") + set(LIBR_LIB_DIR "${LIBR_HOME}/lib" CACHE PATH "R lib directory") endif() # detection for UNIX & Win32 @@ -103,12 +116,15 @@ else() set(LIBR_INCLUDE_DIRS "${LIBR_HOME}/include" CACHE PATH "R include directory") set(LIBR_DOC_DIR "${LIBR_HOME}/doc" CACHE PATH "R doc directory") - # set library hint path based on whether we are doing a special session 64 build - if(LIBR_FIND_WINDOWS_64BIT) - set(LIBRARY_ARCH_HINT_PATH "${LIBR_HOME}/bin/x64") - else() - set(LIBRARY_ARCH_HINT_PATH "${LIBR_HOME}/bin/i386") - endif() + # set library hint path for 64-bit build + set(LIBR_ARCH "x64") + set(LIBRARY_ARCH_HINT_PATH "${LIBR_HOME}/bin/x64") + + # call dll2lib.R to ensure export files are generated + execute_process( + COMMAND "${LIBR_HOME}/bin/${LIBR_ARCH}/Rscript.exe" "dll2lib.R" + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/tools" + RESULT_VARIABLE LIBR_DLL2LIB_RESULT) endif() @@ -173,6 +189,7 @@ find_package_handle_standard_args(LibR DEFAULT_MSG if(LIBR_FOUND) message(STATUS "Found R: ${LIBR_HOME}") + get_filename_component(LIBR_BIN_DIR "${LIBR_EXECUTABLE}" PATH CACHE) endif() # mark low-level variables from FIND_* calls as advanced diff --git a/config.h.cmake b/config.h.cmake index 2bf5293f7..80f3a6854 100644 --- a/config.h.cmake +++ b/config.h.cmake @@ -897,7 +897,7 @@ function. */ #cmakedefine HAVE_MBSNRTOWCS ${HAVE_MBSNRTOWCS} #endif -/* Define to 1 if you have the `memcpy' function. */ +/* Define to 1 if you have the `memmove' function. */ #ifndef HAVE_MEMCPY #cmakedefine HAVE_MEMCPY ${HAVE_MEMCPY} #endif diff --git a/console/LGPL/pl-ntmain.c b/console/LGPL/pl-ntmain.c index fed5daa3a..291e3737e 100755 --- a/console/LGPL/pl-ntmain.c +++ b/console/LGPL/pl-ntmain.c @@ -356,7 +356,7 @@ Srlc_write(void *handle, char *buffer, size_t size) { char buf[sizeof(TCHAR)]; /* Pad to TCHAR */ size_t i = sizeof(TCHAR) - (size-n); - memcpy(buf, buffer+n, i); + memmove(buf, buffer+n, i); for(; i bootstrapping mode: YAP is not properly installed bool install; + //> jupyter mode: YAP is in space + bool jupyter; //> generats a saved space at this path const char *OUTPUT_STARTUP; //> if NON-0, minimal size for Heap or Code Area diff --git a/include/YapErrors.h b/include/YapErrors.h index 484df0451..536a1699e 100644 --- a/include/YapErrors.h +++ b/include/YapErrors.h @@ -21,7 +21,7 @@ ECLASS(INSTANTIATION_ERROR_CLASS, "instantiation_error", 0) /// bad access, I/O ECLASS(PERMISSION_ERROR, "permission_error", 3) /// something that could not be represented into a type -ECLASS(REPRESENTATION_ERROR, "representation_error", 1) +ECLASS(REPRESENTATION_ERROR, "representation_error", 0) /// not enough .... ECLASS(RESOURCE_ERROR, "resource_error", 2) /// bad text diff --git a/library/charsio.yap b/library/charsio.yap index 3adcf64fb..3055dac5b 100644 --- a/library/charsio.yap +++ b/library/charsio.yap @@ -26,7 +26,7 @@ */ -:- module(charsio, [ +:- module(system(charsio), [ format_to_chars/3, format_to_chars/4, write_to_chars/3, diff --git a/library/dialect/swi/fli/swi.c b/library/dialect/swi/fli/swi.c index 059c9a175..568ecf6a2 100755 --- a/library/dialect/swi/fli/swi.c +++ b/library/dialect/swi/fli/swi.c @@ -70,7 +70,6 @@ Moyle. All rights reserved. static atom_t ATOM_nil; -extern int PL_unify_termv(term_t l, va_list args); extern X_API Atom YAP_AtomFromSWIAtom(atom_t at); extern X_API atom_t YAP_SWIAtomFromAtom(Atom at); @@ -818,6 +817,14 @@ X_API int PL_unify_bool(term_t t, int a) { return Yap_unify(Yap_GetFromSlot(t), iterm); } +X_API int PL_put_bool(term_t t, int a) { + CACHE_REGS + CELL *pt = Yap_AddressFromHandle( t ); + Term iterm = (a ? MkAtomTerm(AtomTrue) : MkAtomTerm(AtomFalse)); + *pt = iterm; + return true; +} + #if USE_GMP /******************************* @@ -1273,7 +1280,7 @@ YAP: NO EQUIVALENT */ X_API int PL_raise_exception(term_t exception) { CACHE_REGS LOCAL_Error_TYPE = THROW_EVENT; - LOCAL_ActiveError->errorGoal = Yap_TermToBuffer(Yap_GetFromHandle(exception), LOCAL_encoding, TermNil); + LOCAL_ActiveError->errorGoal = Yap_TermToBuffer(Yap_GetFromHandle(exception), 0); //Yap_PutException(Yap_GetFromSlot(exception)); Yap_RaiseException(); return 0; @@ -1321,7 +1328,7 @@ X_API int PL_unify_atom_chars(term_t t, const char *s) { Atom at; while ((at = Yap_CharsToAtom(s, ENC_ISO_LATIN1 PASS_REGS)) == 0L) { if (LOCAL_Error_TYPE && !Yap_SWIHandleError("PL_unify_atom_nchars")) - return FALSE; + return true; } Yap_AtomIncreaseHold(at); return Yap_unify(Yap_GetFromSlot(t), MkAtomTerm(at)); diff --git a/library/dialect/swi/os/dtoa.c b/library/dialect/swi/os/dtoa.c index 5df81f93e..7b25ce5ae 100644 --- a/library/dialect/swi/os/dtoa.c +++ b/library/dialect/swi/os/dtoa.c @@ -593,7 +593,7 @@ Bfree } } -#define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \ +#define Bcopy(x,y) memmove((char *)&x->sign, (char *)&y->sign, \ y->wds*sizeof(Long) + 2*sizeof(int)) static Bigint * diff --git a/library/dialect/swi/os/pl-buffer.c b/library/dialect/swi/os/pl-buffer.c index e4ea5ff48..c99a4e9c0 100644 --- a/library/dialect/swi/os/pl-buffer.c +++ b/library/dialect/swi/os/pl-buffer.c @@ -42,7 +42,7 @@ growBuffer(Buffer b, size_t minfree) { if ( !(new = malloc(sz)) ) return FALSE; - memcpy(new, b->static_buffer, osz); + memmove(new, b->static_buffer, osz); } else { if ( !(new = realloc(b->base, sz)) ) return FALSE; diff --git a/library/dialect/swi/os/pl-file.c b/library/dialect/swi/os/pl-file.c index 1b9a70644..fc3083728 100644 --- a/library/dialect/swi/os/pl-file.c +++ b/library/dialect/swi/os/pl-file.c @@ -2381,7 +2381,7 @@ re_buffer(IOSTREAM *s, const char *from, size_t len) { s->bufp = s->limitp = s->buffer; } - memcpy(s->bufp, from, len); + memmove(s->bufp, from, len); s->bufp += len; } @@ -5846,7 +5846,7 @@ struct PL_local_data *Yap_InitThreadIO(int wid) return p; } #if THREADS - memcpy(p, Yap_local[0]->PL_local_data_p_, sizeof(struct PL_local_data)); + memmove(p, Yap_local[0]->PL_local_data_p_, sizeof(struct PL_local_data)); #endif return p; } diff --git a/library/dialect/swi/os/pl-fmt.c b/library/dialect/swi/os/pl-fmt.c index 7ef3b45f2..9aedb2ae4 100644 --- a/library/dialect/swi/os/pl-fmt.c +++ b/library/dialect/swi/os/pl-fmt.c @@ -1426,7 +1426,7 @@ localizeDecimalPoint(PL_locale *locale, Buffer b) if ( strncmp(e, ddp, ddplen) == 0 ) { if ( dplen == ddplen ) - { memcpy(e, dp, dplen); + { memmove(e, dp, dplen); } else { char *ob = baseBuffer(b, char); if ( dplen > ddplen && !growBuffer(b, dplen-ddplen) ) @@ -1434,7 +1434,7 @@ localizeDecimalPoint(PL_locale *locale, Buffer b) e += baseBuffer(b, char) - ob; memmove(&e[dplen-ddplen], e, strlen(e)+1); - memcpy(e, dp, dplen); + memmove(e, dp, dplen); } } } @@ -1477,7 +1477,7 @@ groupDigits(PL_locale *locale, Buffer b) { *o-- = *e--; if ( --gsize == 0 && e>=s ) { o -= thslen-1; - memcpy(o, ths, thslen); + memmove(o, ths, thslen); o--; if ( grouping[1] == 0 ) gsize = grouping[0]; diff --git a/library/dialect/swi/os/pl-nt.c b/library/dialect/swi/os/pl-nt.c index 3486dcfbd..b7d204de1 100755 --- a/library/dialect/swi/os/pl-nt.c +++ b/library/dialect/swi/os/pl-nt.c @@ -429,7 +429,7 @@ win_exec(size_t len, const wchar_t *cmd, UINT show) /* ensure 0-terminated */ wcmd = PL_malloc((len+1)*sizeof(wchar_t)); - memcpy(wcmd, cmd, len*sizeof(wchar_t)); + memmove(wcmd, cmd, len*sizeof(wchar_t)); wcmd[len] = 0; rval = CreateProcessW(NULL, /* app */ diff --git a/library/dialect/swi/os/pl-os.c b/library/dialect/swi/os/pl-os.c index ecfa30510..f144fde79 100755 --- a/library/dialect/swi/os/pl-os.c +++ b/library/dialect/swi/os/pl-os.c @@ -953,7 +953,7 @@ getenv3(const char *name, char *buf, size_t len) if ( s ) { if ( (l=strlen(s)) < len ) - memcpy(buf, s, l+1); + memmove(buf, s, l+1); else if ( len > 0 ) buf[0] = EOS; /* empty string if not fit */ diff --git a/library/dialect/swi/os/pl-read.c b/library/dialect/swi/os/pl-read.c index 45381df79..a96c5f5f6 100644 --- a/library/dialect/swi/os/pl-read.c +++ b/library/dialect/swi/os/pl-read.c @@ -253,7 +253,7 @@ static void growToBuffer(int c, ReadData _PL_rd) { if (rb.base == rb.fast) /* intptr_t clause: jump to use malloc() */ { rb.base = PL_malloc(FASTBUFFERSIZE * 2); - memcpy(rb.base, rb.fast, FASTBUFFERSIZE); + memmove(rb.base, rb.fast, FASTBUFFERSIZE); } else rb.base = PL_realloc(rb.base, rb.size * 2); diff --git a/library/dialect/swi/os/pl-rl.c b/library/dialect/swi/os/pl-rl.c index 76ab00cab..4a8abc72b 100755 --- a/library/dialect/swi/os/pl-rl.c +++ b/library/dialect/swi/os/pl-rl.c @@ -491,7 +491,7 @@ Sread_readline(void *handle, char *buf, size_t size) { PL_warning("Input line too long"); /* must be tested! */ l = size-1; } - memcpy(buf, line, l); + memmove(buf, line, l); buf[l++] = '\n'; rval = l; diff --git a/library/dialect/swi/os/pl-stream.c b/library/dialect/swi/os/pl-stream.c index a69c62028..f8ab272f0 100755 --- a/library/dialect/swi/os/pl-stream.c +++ b/library/dialect/swi/os/pl-stream.c @@ -239,7 +239,7 @@ S__setbuf(IOSTREAM *s, char *buffer, size_t size) } } - memcpy(newbuf, s->bufp, copy); + memmove(newbuf, s->bufp, copy); S__removebuf(s); s->unbuffer = newunbuf; s->bufp = s->buffer = newbuf; @@ -1173,7 +1173,7 @@ Speekcode(IOSTREAM *s) if ( s->bufp + UNDO_SIZE > s->limitp && !(s->flags&SIO_USERBUF) ) { safe = s->limitp - s->bufp; - memcpy(s->buffer-safe, s->bufp, safe); + memmove(s->buffer-safe, s->bufp, safe); } start = s->bufp; @@ -1262,11 +1262,11 @@ Sfread(void *data, size_t size, size_t elms, IOSTREAM *s) { size_t avail = s->limitp - s->bufp; if ( chars <= avail ) - { memcpy(buf, s->bufp, chars); + { memmove(buf, s->bufp, chars); s->bufp += chars; return elms; } else - { memcpy(buf, s->bufp, avail); + { memmove(buf, s->bufp, avail); chars -= avail; buf += avail; s->bufp += avail; @@ -1325,7 +1325,7 @@ Sread_pending(IOSTREAM *s, char *buf, size_t limit, int flags) n = s->limitp - s->bufp; if ( n > limit ) n = limit; - memcpy(&buf[done], s->bufp, n); + memmove(&buf[done], s->bufp, n); s->bufp += n; return done+n; @@ -3439,7 +3439,7 @@ Swrite_memfile(void *handle, char *buf, size_t size) } if ( !mf->malloced ) { if ( mf->buffer ) - memcpy(nb, mf->buffer, mf->allocated); + memmove(nb, mf->buffer, mf->allocated); mf->malloced = TRUE; } } else @@ -3453,7 +3453,7 @@ Swrite_memfile(void *handle, char *buf, size_t size) *mf->bufferp = mf->buffer = nb; } - memcpy(&mf->buffer[mf->here], buf, size); + memmove(&mf->buffer[mf->here], buf, size); mf->here += size; if ( mf->here > mf->size ) @@ -3478,7 +3478,7 @@ Sread_memfile(void *handle, char *buf, size_t size) size = mf->size - mf->here; } - memcpy(buf, &mf->buffer[mf->here], size); + memmove(buf, &mf->buffer[mf->here], size); mf->here += size; return size; diff --git a/library/dialect/swi/os/pl-text.c b/library/dialect/swi/os/pl-text.c index 29b2668db..c800224f5 100644 --- a/library/dialect/swi/os/pl-text.c +++ b/library/dialect/swi/os/pl-text.c @@ -69,7 +69,7 @@ PL_save_text(PL_chars_t *text, int flags) { size_t bl = bufsize_text(text, text->length+1); void *new = PL_malloc(bl); - memcpy(new, text->text.t, bl); + memmove(new, text->text.t, bl); text->text.t = new; text->storage = PL_CHARS_MALLOC; } else if ( text->storage == PL_CHARS_LOCAL ) @@ -104,7 +104,7 @@ PL_from_stack_text(PL_chars_t *text) { size_t bl = bufsize_text(text, text->length+1); if ( bl < sizeof(text->buf) ) - { memcpy(text->buf, text->text.t, bl); + { memmove(text->buf, text->text.t, bl); text->text.t = text->buf; text->storage = PL_CHARS_LOCAL; } else @@ -135,7 +135,7 @@ ui64toa(uint64_t val, char *out) } while ( val ); nbDigs = ptrOrg - ptr; - memcpy(out, ptr, nbDigs); + memmove(out, ptr, nbDigs); out += nbDigs; *out = '\0'; @@ -610,7 +610,7 @@ PL_promote_text(PL_chars_t *text) unsigned char *e = &buf[text->length]; pl_wchar_t *t = (pl_wchar_t*)text->buf; - memcpy(buf, text->buf, text->length*sizeof(char)); + memmove(buf, text->buf, text->length*sizeof(char)); while(flength]; char *t = text->buf; - memcpy(buf, text->buf, text->length*sizeof(pl_wchar_t)); + memmove(buf, text->buf, text->length*sizeof(pl_wchar_t)); while(f 0xff ) return FALSE; @@ -1021,7 +1021,7 @@ PL_canonise_text(PL_chars_t *text) text->encoding = ENC_WCHAR; if ( len+1 < sizeof(text->buf)/sizeof(wchar_t) ) { if ( text->text.t == text->buf ) - { memcpy(b2, text->buf, sizeof(text->buf)); + { memmove(b2, text->buf, sizeof(text->buf)); from = b2; } text->text.w = (wchar_t*)text->buf; @@ -1239,7 +1239,7 @@ PL_concat_text(int n, PL_chars_t **text, PL_chars_t *result) } for(to=result->text.t, i=0; itext.t, text[i]->length); + { memmove(to, text[i]->text.t, text[i]->length); to += text[i]->length; } *to = EOS; @@ -1257,7 +1257,7 @@ PL_concat_text(int n, PL_chars_t **text, PL_chars_t *result) for(to=result->text.w, i=0; iencoding == ENC_WCHAR ) - { memcpy(to, text[i]->text.w, text[i]->length*sizeof(pl_wchar_t)); + { memmove(to, text[i]->text.w, text[i]->length*sizeof(pl_wchar_t)); to += text[i]->length; } else { const unsigned char *f = (const unsigned char *)text[i]->text.t; diff --git a/library/dialect/swi/os/pl-write.c b/library/dialect/swi/os/pl-write.c index 94b19503f..9c0a7e3ec 100644 --- a/library/dialect/swi/os/pl-write.c +++ b/library/dialect/swi/os/pl-write.c @@ -137,7 +137,7 @@ format_float(double f, char *buf) { *o++ = s[0]; *o++ = '.'; if ( end-s > 1 ) - { memcpy(o, s+1, end-s-1); + { memmove(o, s+1, end-s-1); o += end-s-1; } else *o++ = '0'; @@ -149,14 +149,14 @@ format_float(double f, char *buf) *o++ = '.'; for(i=0; i < -decpt; i++) *o++ = '0'; - memcpy(o, s, end-s); + memmove(o, s, end-s); o[end-s] = 0; } } else if ( end-s > decpt ) /* decimal dot inside */ - { memcpy(o, s, decpt); + { memmove(o, s, decpt); o += decpt; *o++ = '.'; - memcpy(o, s+decpt, end-s-decpt); + memmove(o, s+decpt, end-s-decpt); o[end-s-decpt] = 0; } else /* decimal dot after */ { int i; @@ -167,13 +167,13 @@ format_float(double f, char *buf) *o++ = '.'; if ( end-s > 1 ) { trailing += (int)(end-s)-1; - memcpy(o, s+1, end-s-1); + memmove(o, s+1, end-s-1); o += end-s-1; } else *o++ = '0'; sprintf(o, "e+%d", trailing); } else /* within precision trail with .0 */ - { memcpy(o, s, end-s); + { memmove(o, s, end-s); o += end-s; for(i=(int)(end-s); issize + len); /* this many unexpected additions */ assert(p->ssize >= p->slen + len); - (void)memcpy((char *)(p->strip + p->slen), (char *)(p->strip + start), + (void)memmove((char *)(p->strip + p->slen), (char *)(p->strip + start), (size_t)len * sizeof(sop)); p->slen += len; return (ret); diff --git a/library/regex/regexec.c b/library/regex/regexec.c index c4499d2ce..6796be90a 100644 --- a/library/regex/regexec.c +++ b/library/regex/regexec.c @@ -130,7 +130,7 @@ static int nope = 0; /* for use in asserts; shuts lint up */ #define SET0(v, n) ((v)[n] = 0) #define SET1(v, n) ((v)[n] = 1) #define ISSET(v, n) ((v)[n]) -#define ASSIGN(d, s) memcpy(d, s, m->g->nstates) +#define ASSIGN(d, s) memmove(d, s, m->g->nstates) #define EQ(a, b) (memcmp(a, b, m->g->nstates) == 0) #define STATEVARS \ long vn; \ diff --git a/library/rltree/range_list.c b/library/rltree/range_list.c index b7cd3aa53..05a3778f5 100644 --- a/library/rltree/range_list.c +++ b/library/rltree/range_list.c @@ -153,8 +153,8 @@ RL_Tree *copy_rl(RL_Tree *tree) { free(new); return NULL; } - memcpy(new, tree, sizeof(RL_Tree)); - memcpy(buf_ptr, &tree->root[0], tree->size * NODE_SIZE); + memmove(new, tree, sizeof(RL_Tree)); + memmove(buf_ptr, &tree->root[0], tree->size * NODE_SIZE); new->root = buf_ptr; new->mem_alloc = tree->size *NODE_SIZE; return new; diff --git a/library/system/crypto/md5.c b/library/system/crypto/md5.c index 8fdc60072..9dc80d7d6 100644 --- a/library/system/crypto/md5.c +++ b/library/system/crypto/md5.c @@ -167,7 +167,7 @@ md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) X = (const md5_word_t *)data; } else { /* not aligned */ - memcpy(xbuf, data, 64); + memmove(xbuf, data, 64); X = xbuf; } } @@ -353,7 +353,7 @@ md5_append(md5_state_t *pms, const md5_byte_t *data, unsigned int nbytes) if (offset) { unsigned int copy = (offset + nbytes > 64 ? 64 - offset : nbytes); - memcpy(pms->buf + offset, p, copy); + memmove(pms->buf + offset, p, copy); if (offset + copy < 64) return; p += copy; @@ -367,7 +367,7 @@ md5_append(md5_state_t *pms, const md5_byte_t *data, unsigned int nbytes) /* Process a final partial block. */ if (left) - memcpy(pms->buf, p, left); + memmove(pms->buf, p, left); } void diff --git a/library/tries/base_itries.h b/library/tries/base_itries.h index 11a08eef9..96a90fd77 100644 --- a/library/tries/base_itries.h +++ b/library/tries/base_itries.h @@ -114,7 +114,7 @@ typedef struct itrie_data { YAP_Int i, new_num_buckets = DEPTH + BASE_TR_DATA_BUCKETS; \ bucket = TrEntry_buckets(TR_ENTRY); \ new_itrie_buckets(TR_ENTRY, new_num_buckets); \ - memcpy(TrEntry_buckets(TR_ENTRY), bucket, \ + memmove(TrEntry_buckets(TR_ENTRY), bucket, \ TrEntry_num_buckets(TR_ENTRY) * SIZEOF_TR_DATA_BUCKET); \ free_itrie_buckets(bucket, TrEntry_num_buckets(TR_ENTRY)); \ bucket = TrEntry_buckets(TR_ENTRY); \ diff --git a/library/tries/core_tries.c b/library/tries/core_tries.c index f66380be2..c42602059 100644 --- a/library/tries/core_tries.c +++ b/library/tries/core_tries.c @@ -1468,12 +1468,12 @@ void traverse_and_print(TrNode node, int *arity, char *str, int str_index, int m hash = (TrHash) node; first_bucket = TrHash_buckets(hash); bucket = first_bucket + TrHash_num_buckets(hash); - memcpy(current_arity, arity, sizeof(int) * (arity[0] + 1)); + memmove(current_arity, arity, sizeof(int) * (arity[0] + 1)); do { if (*--bucket) { node = *bucket; traverse_and_print(node, arity, str, str_index, mode); - memcpy(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); + memmove(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); if (mode != TRIE_PRINT_FLOAT2 && arity[arity[0]] < 0) { /* restore possible PairEndEmptyTag/PairEndTermTag/CommaEndTag side-effect */ if (str_index > 0 && str[str_index - 1] != '[') @@ -1490,9 +1490,9 @@ void traverse_and_print(TrNode node, int *arity, char *str, int str_index, int m if (TrNode_next(node)) { int *current_arity = (int *) malloc(sizeof(int) * (arity[0] + 1)); - memcpy(current_arity, arity, sizeof(int) * (arity[0] + 1)); + memmove(current_arity, arity, sizeof(int) * (arity[0] + 1)); traverse_and_print(TrNode_next(node), arity, str, str_index, mode); - memcpy(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); + memmove(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); if (mode != TRIE_PRINT_FLOAT2 && arity[arity[0]] < 0) { /* restore possible PairEndEmptyTag/PairEndTermTag/CommaEndTag side-effect */ if (str_index > 0 && str[str_index - 1] != '[') diff --git a/library/tries/core_tries.h b/library/tries/core_tries.h index cced2cb4a..4bfaf47f8 100644 --- a/library/tries/core_tries.h +++ b/library/tries/core_tries.h @@ -221,7 +221,7 @@ typedef struct trie_hash { { YAP_Term *aux_stack; \ YAP_Int aux_size = CURRENT_AUXILIARY_TERM_STACK_SIZE * sizeof(YAP_Term); \ new_struct(aux_stack, YAP_Term, aux_size * 2); \ - memcpy(aux_stack, AUXILIARY_TERM_STACK, aux_size); \ + memmove(aux_stack, AUXILIARY_TERM_STACK, aux_size); \ free_struct(AUXILIARY_TERM_STACK); \ AUXILIARY_TERM_STACK = aux_stack; \ CURRENT_AUXILIARY_TERM_STACK_SIZE *= 2; \ diff --git a/os/alias.c b/os/alias.c index 2a92e652f..6b8534bb6 100644 --- a/os/alias.c +++ b/os/alias.c @@ -209,7 +209,7 @@ ExtendAliasArray(void) UInt new_size = GLOBAL_SzOfFileAliases+ALIASES_BLOCK_SIZE; new = (AliasDesc)Yap_AllocCodeSpace(sizeof(AliasDesc *)*new_size); - memcpy((void *)new, (void *)GLOBAL_FileAliases, sizeof(AliasDesc *)*GLOBAL_SzOfFileAliases); + memmove((void *)new, (void *)GLOBAL_FileAliases, sizeof(AliasDesc *)*GLOBAL_SzOfFileAliases); Yap_FreeCodeSpace((ADDR) GLOBAL_FileAliases); GLOBAL_FileAliases = new; GLOBAL_SzOfFileAliases = new_size; @@ -221,16 +221,16 @@ Yap_SetAlias (Atom arg, int sno) CACHE_REGS AliasDesc aliasp = GLOBAL_FileAliases, aliasp_max = GLOBAL_FileAliases+GLOBAL_NOfFileAliases; - while (aliasp < aliasp_max) { - // replace alias - if (aliasp->name == arg) { - aliasp->alias_stream = sno; if (arg == AtomUserIn) LOCAL_c_input_stream = sno; if (arg == AtomUserOut) LOCAL_c_output_stream = sno; if (arg == AtomUserErr) LOCAL_c_error_stream = sno; + while (aliasp < aliasp_max) { + // replace alias + if (aliasp->name == arg) { + aliasp->alias_stream = sno; return; } aliasp++; @@ -317,16 +317,16 @@ ExistsAliasForStream (int sno, Atom al) while (aliasp < aliasp_max) { if (aliasp->alias_stream == sno && aliasp->name == al) { if (al == AtomUserIn) { - LOCAL_c_input_stream = StdInStream; - aliasp->alias_stream = StdInStream; - } + LOCAL_c_input_stream = sno; + aliasp->alias_stream = sno; + } else if (al == AtomUserOut) { - LOCAL_c_output_stream = StdOutStream; - aliasp->alias_stream = StdOutStream; + LOCAL_c_output_stream = sno; + aliasp->alias_stream = sno; } if (al == AtomUserErr) { - LOCAL_c_error_stream = StdErrStream; - aliasp->alias_stream = StdErrStream; + LOCAL_c_error_stream = sno; + aliasp->alias_stream = sno; } return true; } @@ -387,6 +387,12 @@ Yap_AddAlias (Atom arg, int sno) AliasDesc aliasp = GLOBAL_FileAliases, aliasp_max = GLOBAL_FileAliases+GLOBAL_NOfFileAliases; + if (arg == AtomUserIn) + LOCAL_c_input_stream = sno; + else if (arg == AtomUserOut) + LOCAL_c_output_stream = sno; + else if (arg == AtomUserErr) + LOCAL_c_error_stream = sno; while (aliasp < aliasp_max) { if (aliasp->name == arg) { aliasp->alias_stream = sno; @@ -394,6 +400,7 @@ Yap_AddAlias (Atom arg, int sno) } aliasp++; } + /* we have not found an alias neither a hole */ if (aliasp == GLOBAL_FileAliases+GLOBAL_SzOfFileAliases) ExtendAliasArray(); diff --git a/os/assets.c b/os/assets.c index 8243d4ae3..ed1dac028 100644 --- a/os/assets.c +++ b/os/assets.c @@ -98,12 +98,12 @@ open_asset(VFS_t *me, const char *fname, const char *io_mode, int sno) { if ((buf = AAsset_getBuffer(am))) { // copy to memory char *bf = malloc(sz); - memcpy(bf, buf, sz); + memmove(bf, buf, sz); bool rc = Yap_set_stream_to_buf(st, bf, sz); if (rc) AAsset_close(am); st->vfs = NULL; st->vfs_handle = NULL; - st->status = InMemory_Stream_f|Seekable_Stream_f|Input_Stream_f; + st->status = InMemory_Stream_f|Seekable_Stream_f|Input_Stream_f; return st; } else if ((fd = AAsset_openFileDescriptor64(am, &sz0, &sz)) >= 0) { // can use it as read-only file @@ -162,10 +162,10 @@ static bool stat_a(VFS_t *me, const char *fname, vfs_stat *out) { out->st_dev = bf.st_dev; out->st_uid = bf.st_uid; out->st_gid = bf.st_gid; - memcpy(&out->st_atimespec, (const void *) &bf.st_atim, sizeof(struct timespec)); - memcpy(&out->st_mtimespec, (const void *) &bf.st_mtim, sizeof(struct timespec)); - memcpy(&out->st_ctimespec, (const void *) &bf.st_ctim, sizeof(struct timespec)); - memcpy(&out->st_birthtimespec, (const void *) &bf.st_ctim, + memmove(&out->st_atimespec, (const void *) &bf.st_atim, sizeof(struct timespec)); + memmove(&out->st_mtimespec, (const void *) &bf.st_mtim, sizeof(struct timespec)); + memmove(&out->st_ctimespec, (const void *) &bf.st_ctim, sizeof(struct timespec)); + memmove(&out->st_birthtimespec, (const void *) &bf.st_ctim, sizeof(struct timespec)); } AAsset *a = AAssetManager_open(Yap_assetManager(), fname, AASSET_MODE_UNKNOWN); diff --git a/os/charsio.c b/os/charsio.c index f2205d8c5..f531d312e 100644 --- a/os/charsio.c +++ b/os/charsio.c @@ -990,16 +990,11 @@ leaving the current stream position unaltered. */ static Int peek_code(USES_REGS1) { /* at_end_of_stream */ /* the next character is a EOF */ - int sno = Yap_CheckTextStream(ARG1, Input_Stream_f, "peek/2"); + int sno = Yap_CheckTextStream(ARG1, Input_Stream_f, "peek_code/2"); Int ch; if (sno < 0) return FALSE; - if (GLOBAL_Stream[sno].status & Binary_Stream_f) { - UNLOCK(GLOBAL_Stream[sno].streamlock); - Yap_Error(PERMISSION_ERROR_INPUT_TEXT_STREAM, ARG1, "peek_code/2"); - return FALSE; - } if ((ch = Yap_peek(sno)) < 0) { #ifdef PEEK_EOF UNLOCK(GLOBAL_Stream[sno].streamlock); diff --git a/os/chartypes.c b/os/chartypes.c index a8371c7fc..973f09635 100644 --- a/os/chartypes.c +++ b/os/chartypes.c @@ -82,8 +82,8 @@ Term Yap_StringToNumberTerm(const char *s, encoding_t *encp, bool error_on) { CACHE_REGS int sno; int i = push_text_stack(); - - sno = Yap_open_buf_read_stream(s, strlen(s), encp, MEM_BUF_USER); + Atom nat = Yap_LookupAtom(Yap_StrPrefix(s, 16)); + sno = Yap_open_buf_read_stream(s, strlen(s), encp, MEM_BUF_USER, nat, MkAtomTerm(Yap_LookupAtom("eval"))); if (sno < 0) return FALSE; if (encp) diff --git a/os/files.c b/os/files.c index 9a37819a9..b7e9e5ca5 100644 --- a/os/files.c +++ b/os/files.c @@ -98,7 +98,7 @@ static Int file_name_extension(USES_REGS1) { ext = ""; } base = Malloc(lenb_b + 1); - memcpy(base, f, lenb_b); + memmove(base, f, lenb_b); base[lenb_b] = '\0'; if (IsVarTerm(t1 = Deref(ARG1))) { // should always succeed diff --git a/os/fmem.c b/os/fmem.c index 7d99fabe1..53f9274ca 100644 --- a/os/fmem.c +++ b/os/fmem.c @@ -131,8 +131,18 @@ bool Yap_set_stream_to_buf(StreamDesc *st, const char *buf, return true; } -int Yap_open_buf_read_stream(const char *buf, size_t nchars, encoding_t *encp, - memBufSource src) { + + char *Yap_StrPrefix( const char *buf, size_t n) { + char *b = (char*)malloc(n); + strncpy(b, buf, n - 1); + if (strlen(buf) > n - 1) + b[15] = '\0'; + return b; +} + +int Yap_open_buf_read_stream(const char *buf, size_t nchars, + encoding_t *encp, memBufSource src, Atom fname, + Term uname) { CACHE_REGS int sno; StreamDesc *st; @@ -153,7 +163,7 @@ int Yap_open_buf_read_stream(const char *buf, size_t nchars, encoding_t *encp, f = st->file = fmemopen((void *)buf, nchars, "r"); st->vfs = NULL; flags = Input_Stream_f | InMemory_Stream_f | Seekable_Stream_f; - Yap_initStream(sno, f, "memStream", "r", TermNone, encoding, flags, NULL); + Yap_initStream(sno, f, RepAtom(fname)->StrOfAE, "r", uname, encoding, flags, NULL); // like any file stream. Yap_DefaultStreamOps(st); UNLOCK(st->streamlock); @@ -176,7 +186,7 @@ open_mem_read_stream(USES_REGS1) /* $open_mem_read_stream(+List,-Stream) */ } buf = pop_output_text_stack(l, buf); sno = Yap_open_buf_read_stream(buf, strlen(buf) + 1, &LOCAL_encoding, - MEM_BUF_MALLOC); + MEM_BUF_MALLOC, Yap_LookupAtom(Yap_StrPrefix((char *)buf,16)), TermNone); t = Yap_MkStream(sno); return Yap_unify(ARG2, t); } @@ -193,7 +203,9 @@ int Yap_open_buf_write_stream(encoding_t enc, memBufSource src) { return -1; st = GLOBAL_Stream + sno; - st->status = Output_Stream_f | InMemory_Stream_f | FreeOnClose_Stream_f; + st->status = Output_Stream_f | InMemory_Stream_f; + if (st->nbuf) + st->status |= FreeOnClose_Stream_f; st->linepos = 0; st->charcount = 0; st->linecount = 1; @@ -202,15 +214,15 @@ int Yap_open_buf_write_stream(encoding_t enc, memBufSource src) { st->buf.on = true; st->nbuf = NULL; st->nsize = 0; + st->status |= Seekable_Stream_f; #if HAVE_OPEN_MEMSTREAM st->file = open_memstream(&st->nbuf, &st->nsize); // setbuf(st->file, NULL); - st->status |= Seekable_Stream_f; -#else - st->file = fmemopen((void *)st->nbuf, st->nsize, "w"); if (!st->nbuf) { return -1; } +#else + st->file = fmemopen((void *)st->nbuf, st->nsize, "w+"); #endif Yap_DefaultStreamOps(st); UNLOCK(st->streamlock); @@ -247,35 +259,41 @@ open_mem_write_stream(USES_REGS1) /* $open_mem_write_stream(-Stream) */ * by other writes.. */ char *Yap_MemExportStreamPtr(int sno) { - char *s; - if (fflush(GLOBAL_Stream[sno].file) == 0) { - s = GLOBAL_Stream[sno].nbuf; - // s[fseek(GLOBAL_Stream[sno].file, 0, SEEK_END)] = '\0'; - return s; + + if (fflush(GLOBAL_Stream[sno].file) < 0) { + return NULL; } - return NULL; + size_t len = fseek(GLOBAL_Stream[sno].file, 0, SEEK_END); + char *buf = malloc(len+1); +#if HAVE_OPEN_MEMSTREAM + char *s = GLOBAL_Stream[sno].nbuf; + memcpy(buf, s, len); + // s[fseek(GLOBAL_Stream[sno].file, 0, SEEK_END)] = '\0'; +#else + fread(buf, sz, 1, GLOBAL_Stream[sno].file); +#endif + buf[len] = '\0'; + return buf; } static Int peek_mem_write_stream( USES_REGS1) { /* '$peek_mem_write_stream'(+GLOBAL_Stream,?S0,?S) */ Int sno = Yap_CheckStream(ARG1, (Output_Stream_f | InMemory_Stream_f), "close/2"); - Int i; Term tf = ARG2; CELL *HI; - const char *ptr; + char *ptr; + int ch; if (sno < 0) return (FALSE); -restart: + char *p = ptr = Yap_MemExportStreamPtr(sno); + restart: HI = HR; - if (fflush(GLOBAL_Stream[sno].file) == 0) { - i = fseek(GLOBAL_Stream[sno].file, 0, SEEK_END); - ptr = GLOBAL_Stream[sno].nbuf; - } - while (i > 0) { - --i; - tf = MkPairTerm(MkIntTerm(ptr[i]), tf); + while ((ch = *p++)) { + HR[0] = MkIntTerm(ch); + HR[1] = AbsPair(HR+2); + HR += 2; if (HR + 1024 >= ASP) { UNLOCK(GLOBAL_Stream[sno].streamlock); HR = HI; @@ -284,14 +302,14 @@ restart: Yap_Error(RESOURCE_ERROR_STACK, TermNil, LOCAL_ErrorMessage); return (FALSE); } - i = GLOBAL_Stream[sno].u.mem_string.pos; - tf = ARG2; LOCK(GLOBAL_Stream[sno].streamlock); goto restart; } } + HR[-1] = tf; UNLOCK(GLOBAL_Stream[sno].streamlock); - return (Yap_unify(ARG3, tf)); + free(ptr); + return (Yap_unify(ARG3, AbsPair(HI))); } void Yap_MemOps(StreamDesc *st) { diff --git a/os/fmemopen-android.c b/os/fmemopen-android.c index 8d698898e..e3d349b9e 100644 --- a/os/fmemopen-android.c +++ b/os/fmemopen-android.c @@ -96,7 +96,7 @@ fmemread(void *cookie, char *buf, int n) return 0; if (n >= c->eof - c->pos) n = c->eof - c->pos; - memcpy (buf, c->buf + c->pos, n); + memmove (buf, c->buf + c->pos, n); c->pos += n; return n; } @@ -144,7 +144,7 @@ fmemwrite(void *cookie, const char *buf, int n) } c->pos += n; if (n - adjust) - memcpy (c->buf + c->pos - n, buf, n - adjust); + memmove (c->buf + c->pos - n, buf, n - adjust); else { return EOF; diff --git a/os/fmemopen.c b/os/fmemopen.c index e8f061f94..3e25c9d3f 100644 --- a/os/fmemopen.c +++ b/os/fmemopen.c @@ -45,7 +45,7 @@ static int readfn(void *handler, char *buf, int size) { if (size > available) { size = available; } - memcpy(buf, mem->buffer + mem->pos, sizeof(char) * size); + memmove(buf, mem->buffer + mem->pos, sizeof(char) * size); mem->pos += size; return size; @@ -58,7 +58,7 @@ static int writefn(void *handler, const char *buf, int size) { if (size > available) { size = available; } - memcpy(mem->buffer + mem->pos, buf, sizeof(char) * size); + memmove(mem->buffer + mem->pos, buf, sizeof(char) * size); mem->pos += size; return size; diff --git a/os/iopreds.c b/os/iopreds.c index a36d2d6aa..fee269474 100644 --- a/os/iopreds.c +++ b/os/iopreds.c @@ -1129,10 +1129,14 @@ static void check_bom(int sno, StreamDesc *st) { bool Yap_initStream(int sno, FILE *fd, const char *name, const char *io_mode, Term file_name, encoding_t encoding, stream_flags_t flags, void *vfs) { + // fprintf(stderr,"+ %s --> %d\n", name, sno); StreamDesc *st = &GLOBAL_Stream[sno]; - __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "init %s %s stream <%d>",io_mode,name, - sno); - if (io_mode == NULL) + __android_log_print( + ANDROID_LOG_INFO, "YAPDroid", "init %s %s:%s stream <%d>", io_mode, + CurrentModule == 0 ? "prolog" + : RepAtom(AtomOfTerm(CurrentModule))->StrOfAE, + name, sno); + if (io_mode == NULL) Yap_Error(PERMISSION_ERROR_NEW_ALIAS_FOR_STREAM, MkIntegerTerm(sno), "File opened with NULL Permissions"); if (strchr(io_mode, 'a')) { @@ -1229,13 +1233,10 @@ typedef enum open_enum_choices { OPEN_DEFS() } open_choices_t; static const param_t open_defs[] = {OPEN_DEFS()}; #undef PAR - -static bool fill_stream(int sno, StreamDesc *st, Term tin, const char *io_mode, Term user_name, - encoding_t enc) -{ +static bool fill_stream(int sno, StreamDesc *st, Term tin, const char *io_mode, + Term user_name, encoding_t enc) { struct vfs *vfsp = NULL; const char *fname; - if (IsAtomTerm(tin)) fname = RepAtom(AtomOfTerm(tin))->StrOfAE; @@ -1287,8 +1288,10 @@ static bool fill_stream(int sno, StreamDesc *st, Term tin, const char *io_mode, return false; } buf = pop_output_text_stack(i, buf); + Atom nat = Yap_LookupAtom(Yap_StrPrefix(buf, 32)); sno = Yap_open_buf_read_stream(buf, strlen(buf) + 1, &LOCAL_encoding, - MEM_BUF_MALLOC); + MEM_BUF_MALLOC, nat, + MkAtomTerm(NameOfFunctor(f))); return Yap_OpenBufWriteStream(PASS_REGS1); } } else if (!strcmp(RepAtom(NameOfFunctor(f))->StrOfAE, "popen")) { @@ -1360,9 +1363,9 @@ static Int do_open(Term file_name, Term t2, Term tlist USES_REGS) { } else { open_mode = AtomOfTerm(t2); } - /* get options */ - xarg *args = Yap_ArgListToVector(tlist, open_defs, OPEN_END, - DOMAIN_ERROR_OPEN_OPTION); + /* get options */ + xarg *args = + Yap_ArgListToVector(tlist, open_defs, OPEN_END, DOMAIN_ERROR_OPEN_OPTION); if (args == NULL) { if (LOCAL_Error_TYPE != YAP_NO_ERROR) { Yap_Error(LOCAL_Error_TYPE, tlist, "option handling in open/3"); @@ -1371,7 +1374,7 @@ static Int do_open(Term file_name, Term t2, Term tlist USES_REGS) { } /* done */ st->status = 0; - const char *s_encoding; + const char *s_encoding; if (args[OPEN_ENCODING].used) { tenc = args[OPEN_ENCODING].tvalue; s_encoding = RepAtom(AtomOfTerm(tenc))->StrOfAE; @@ -1432,14 +1435,14 @@ static Int do_open(Term file_name, Term t2, Term tlist USES_REGS) { "type is ~a, must be one of binary or text", t); } } - + st = &GLOBAL_Stream[sno]; - if (!fill_stream(sno, st, file_name,io_mode,st->user_name,st->encoding)) { + if (!fill_stream(sno, st, file_name, io_mode, st->user_name, st->encoding)) { return false; } -if (args[OPEN_BOM].used) { + if (args[OPEN_BOM].used) { if (args[OPEN_BOM].tvalue == TermTrue) { avoid_bom = false; needs_bom = true; @@ -1667,9 +1670,8 @@ int Yap_OpenStream(Term tin, const char *io_mode, Term user_name, st = GLOBAL_Stream + sno; // fname = Yap_VF(fname); - - if (fill_stream(sno, st, tin,io_mode,user_name,enc)) - return sno; + if (fill_stream(sno, st, tin, io_mode, user_name, enc)) + return sno; return -1; } @@ -1864,13 +1866,13 @@ static Int always_prompt_user(USES_REGS1) { return (TRUE); } - /** @pred close(+ _S_) is iso +/** @pred close(+ _S_) is iso Closes the stream _S_. If _S_ does not stand for a stream currently opened an error is reported. The streams user_input, user_output, and user_error can never be closed. */ - static Int close1(USES_REGS1) { /* '$close'(+GLOBAL_Stream) */ +static Int close1(USES_REGS1) { /* '$close'(+GLOBAL_Stream) */ int sno = CheckStream( ARG1, (Input_Stream_f | Output_Stream_f | Socket_Stream_f), "close/2"); if (sno < 0) diff --git a/os/iopreds.h b/os/iopreds.h index 94ab7a6f0..3980a2efb 100644 --- a/os/iopreds.h +++ b/os/iopreds.h @@ -124,7 +124,6 @@ extern bool Yap_PrintWarning(Term twarning); extern void Yap_plwrite(Term, struct stream_desc *, int, int, int); extern void Yap_WriteAtom(struct stream_desc *s, Atom atom); extern bool Yap_WriteTerm(int output_stream, Term t, Term opts USES_REGS); - extern Term Yap_scan_num(struct stream_desc *, bool); extern void Yap_DefaultStreamOps(StreamDesc *st); diff --git a/os/open_memstream.c b/os/open_memstream.c index 3c32efc74..d8b3928c1 100644 --- a/os/open_memstream.c +++ b/os/open_memstream.c @@ -85,7 +85,7 @@ mem_write (void *c, const char *buf, int n) intermediate bytges are NUL. */ if (cookie->eof < cookie->pos) memset (cbuf + cookie->eof, '\0', cookie->pos - cookie->eof); - memcpy (cbuf + cookie->pos, buf, n); + memmove (cbuf + cookie->pos, buf, n); cookie->pos += n; /* If the user has previously written beyond the current position, remember what the trailing NUL is overwriting. Otherwise, diff --git a/os/readterm.c b/os/readterm.c index 2a5da0ecb..83ff7b055 100644 --- a/os/readterm.c +++ b/os/readterm.c @@ -110,19 +110,19 @@ static void clean_vars(VarEntry *p) { #ifdef O_QUASIQUOTATIONS /** '$qq_open'(+QQRange, -Stream) is det. -Opens a quasi-quoted memory range. + Opens a quasi-quoted memory range. -@arg QQRange is a term '$quasi_quotation'(ReadData, Start, Length) -@arg Stream is a UTF-8 encoded string, whose position indication -reflects the location in the real file. + @arg QQRange is a term '$quasi_quotation'(ReadData, Start, Length) + @arg Stream is a UTF-8 encoded string, whose position indication + reflects the location in the real file. */ static Int qq_open(USES_REGS1) { PRED_LD - Term t = Deref(ARG1); + Term t = Deref(ARG1); if (!IsVarTerm(t) && IsApplTerm(t) && FunctorOfTerm(t) = - FunctorDQuasiQuotation) { + FunctorDQuasiQuotation) { void *ptr; char *start; size_t l int s; @@ -173,27 +173,27 @@ static int parse_quasi_quotations(ReadData _PL_rd ARG_LD) { } else return TRUE; } else if (_PL_rd->quasi_quotations) /* user option, but no quotes */ - { - return PL_unify_nil(_PL_rd->quasi_quotations); - } else + { + return PL_unify_nil(_PL_rd->quasi_quotations); + } else return TRUE; } #endif /*O_QUASIQUOTATIONS*/ -#define READ_DEFS() \ - PAR("comments", list_filler, READ_COMMENTS) \ - , PAR("module", isatom, READ_MODULE), PAR("priority", nat, READ_PRIORITY), \ - PAR("output", filler, READ_OUTPUT), \ - PAR("quasi_quotations", filler, READ_QUASI_QUOTATIONS), \ - PAR("term_position", filler, READ_TERM_POSITION), \ - PAR("syntax_errors", isatom, READ_SYNTAX_ERRORS), \ - PAR("singletons", filler, READ_SINGLETONS), \ - PAR("variables", filler, READ_VARIABLES), \ - PAR("variable_names", filler, READ_VARIABLE_NAMES), \ - PAR("character_escapes", booleanFlag, READ_CHARACTER_ESCAPES), \ - PAR("backquoted_string", isatom, READ_BACKQUOTED_STRING), \ - PAR("cycles", ok, READ_CYCLES), PAR(NULL, ok, READ_END) +#define READ_DEFS() \ + PAR("comments", list_filler, READ_COMMENTS) \ + , PAR("module", isatom, READ_MODULE), PAR("priority", nat, READ_PRIORITY), \ + PAR("output", filler, READ_OUTPUT), \ + PAR("quasi_quotations", filler, READ_QUASI_QUOTATIONS), \ + PAR("term_position", filler, READ_TERM_POSITION), \ + PAR("syntax_errors", isatom, READ_SYNTAX_ERRORS), \ + PAR("singletons", filler, READ_SINGLETONS), \ + PAR("variables", filler, READ_VARIABLES), \ + PAR("variable_names", filler, READ_VARIABLE_NAMES), \ + PAR("character_escapes", booleanFlag, READ_CHARACTER_ESCAPES), \ + PAR("backquoted_string", isatom, READ_BACKQUOTED_STRING), \ + PAR("cycles", ok, READ_CYCLES), PAR(NULL, ok, READ_END) #define PAR(x, y, z) z @@ -201,7 +201,7 @@ typedef enum open_enum_choices { READ_DEFS() } read_choices_t; #undef PAR -#define PAR(x, y, z) \ +#define PAR(x, y, z) \ { x, y, z } static const param_t read_defs[] = {READ_DEFS()}; @@ -284,17 +284,17 @@ static Term scanToList(TokEntry *tok, TokEntry *errtok) { } /** -@pred scan_to_list( +Stream, -Tokens ) -Generate a list of tokens from a scan of the (input) stream, Tokens are of the -form: + @pred scan_to_list( +Stream, -Tokens ) + Generate a list of tokens from a scan of the (input) stream, Tokens are of the + form: -+ `atom`(Atom) -+ ``(Text) -+ `number`(Number) -+ `var`(VarName) -+ `string`(String) -+ 'EOF'' -+ symbols, including `(`, `)`, `,`, `;` + + `atom`(Atom) + + ``(Text) + + `number`(Number) + + `var`(VarName) + + `string`(String) + + 'EOF'' + + symbols, including `(`, `)`, `,`, `;` */ static Int scan_to_list(USES_REGS1) { @@ -307,7 +307,7 @@ static Int scan_to_list(USES_REGS1) { return false; } TokEntry *tok = LOCAL_tokptr = LOCAL_toktide = - Yap_tokenizer(GLOBAL_Stream + inp_stream, false, &tpos); + Yap_tokenizer(GLOBAL_Stream + inp_stream, false, &tpos); UNLOCK(GLOBAL_Stream[inp_stream].streamlock); tout = scanToList(tok, NULL); if (tout == 0) @@ -328,7 +328,7 @@ static Int scan_to_list(USES_REGS1) { */ static Term syntax_error(TokEntry *errtok, int sno, Term cmod, Int newpos) { CACHE_REGS - Term startline, errline, endline; + Term startline, errline, endline; Term tf[4]; Term tm; Term *tailp = tf + 3; @@ -436,7 +436,7 @@ static Term syntax_error(TokEntry *errtok, int sno, Term cmod, Int newpos) { if (Yap_ExecutionMode == YAP_BOOT_MODE) { fprintf(stderr, "SYNTAX ERROR while booting: "); fe - } + } #endif return terr; } @@ -476,11 +476,11 @@ static xarg *setClauseReadEnv(Term opts, FEnv *fe, struct renv *re, int inp_stream); static xarg *setReadEnv(Term opts, FEnv *fe, struct renv *re, int inp_stream) { CACHE_REGS - LOCAL_VarTable = NULL; + LOCAL_VarTable = NULL; LOCAL_AnonVarTable = NULL; fe->enc = GLOBAL_Stream[inp_stream].encoding; xarg *args = - Yap_ArgListToVector(opts, read_defs, READ_END, DOMAIN_ERROR_READ_OPTION); + Yap_ArgListToVector(opts, read_defs, READ_END, DOMAIN_ERROR_READ_OPTION); if (args == NULL) { return NULL; } @@ -561,18 +561,18 @@ static xarg *setReadEnv(Term opts, FEnv *fe, struct renv *re, int inp_stream) { } typedef enum { - YAP_START_PARSING, /// initialization - YAP_SCANNING, /// input to list of tokens - YAP_SCANNING_ERROR, /// serious error (eg oom); trying error handling, followd - /// by either restart or failure - YAP_PARSING, /// list of tokens to term - YAP_PARSING_ERROR, /// oom or syntax error - YAP_PARSING_FINISHED /// exit parser + YAP_START_PARSING, /// initialization + YAP_SCANNING, /// input to list of tokens + YAP_SCANNING_ERROR, /// serious error (eg oom); trying error handling, followd + /// by either restart or failure + YAP_PARSING, /// list of tokens to term + YAP_PARSING_ERROR, /// oom or syntax error + YAP_PARSING_FINISHED /// exit parser } parser_state_t; Int Yap_FirstLineInParse(void) { CACHE_REGS - return LOCAL_StartLineCount; + return LOCAL_StartLineCount; } #define PUSHFET(X) *HR++ = fe->X @@ -581,7 +581,7 @@ Int Yap_FirstLineInParse(void) { static void reset_regs(TokEntry *tokstart, FEnv *fe) { CACHE_REGS - restore_machine_regs(); + restore_machine_regs(); /* restart global */ PUSHFET(qq); @@ -608,7 +608,7 @@ static void reset_regs(TokEntry *tokstart, FEnv *fe) { static Term get_variables(FEnv *fe, TokEntry *tokstart) { CACHE_REGS - Term v; + Term v; if (fe->vp) { while (true) { @@ -628,7 +628,7 @@ static Term get_variables(FEnv *fe, TokEntry *tokstart) { static Term get_varnames(FEnv *fe, TokEntry *tokstart) { CACHE_REGS - Term v; + Term v; if (fe->np) { while (true) { fe->old_H = HR; @@ -648,7 +648,7 @@ static Term get_varnames(FEnv *fe, TokEntry *tokstart) { static Term get_singletons(FEnv *fe, TokEntry *tokstart) { CACHE_REGS - Term v; + Term v; if (fe->sp) { while (TRUE) { fe->old_H = HR; @@ -667,7 +667,7 @@ static Term get_singletons(FEnv *fe, TokEntry *tokstart) { static void warn_singletons(FEnv *fe, TokEntry *tokstart) { CACHE_REGS - Term v; + Term v; fe->sp = TermNil; v = get_singletons(fe, tokstart); if (v && v != TermNil) { @@ -686,7 +686,7 @@ static void warn_singletons(FEnv *fe, TokEntry *tokstart) { static Term get_stream_position(FEnv *fe, TokEntry *tokstart) { CACHE_REGS - Term v; + Term v; if (fe->tp) { while (true) { fe->old_H = HR; @@ -705,7 +705,7 @@ static Term get_stream_position(FEnv *fe, TokEntry *tokstart) { static bool complete_processing(FEnv *fe, TokEntry *tokstart) { CACHE_REGS - Term v1, v2, v3, vc, tp; + Term v1, v2, v3, vc, tp; if (fe->t0 && fe->t && !(Yap_unify(fe->t, fe->t0))) return false; @@ -736,15 +736,15 @@ static bool complete_processing(FEnv *fe, TokEntry *tokstart) { // trail must be ok by now.] if (fe->t) { return (!v1 || Yap_unify(v1, fe->vp)) && (!v2 || Yap_unify(v2, fe->np)) && - (!v3 || Yap_unify(v3, fe->sp)) && (!tp || Yap_unify(tp, fe->tp)) && - (!vc || Yap_unify(vc, fe->tcomms)); + (!v3 || Yap_unify(v3, fe->sp)) && (!tp || Yap_unify(tp, fe->tp)) && + (!vc || Yap_unify(vc, fe->tcomms)); } return true; } static bool complete_clause_processing(FEnv *fe, TokEntry *tokstart) { CACHE_REGS - Term v_vp, v_vnames, v_comments, v_pos; + Term v_vp, v_vnames, v_comments, v_pos; if (fe->t0 && fe->t && !Yap_unify(fe->t, fe->t0)) return false; @@ -772,9 +772,9 @@ static bool complete_clause_processing(FEnv *fe, TokEntry *tokstart) { // trail must be ok by now.] if (fe->t) { return (!v_vp || Yap_unify(v_vp, fe->vp)) && - (!v_vnames || Yap_unify(v_vnames, fe->np)) && - (!v_pos || Yap_unify(v_pos, fe->tp)) && - (!v_comments || Yap_unify(v_comments, fe->tcomms)); + (!v_vnames || Yap_unify(v_vnames, fe->np)) && + (!v_pos || Yap_unify(v_pos, fe->tp)) && + (!v_comments || Yap_unify(v_comments, fe->tcomms)); } return true; } @@ -792,8 +792,8 @@ static parser_state_t scan(REnv *re, FEnv *fe, int inp_stream); static parser_state_t scanEOF(FEnv *fe, int inp_stream) { CACHE_REGS - // bool store_comments = false; - TokEntry *tokstart = LOCAL_tokptr; + // bool store_comments = false; + TokEntry *tokstart = LOCAL_tokptr; // check for an user abort if (tokstart != NULL && tokstart->Tok != Ord(eot_tok)) { /* we got the end of file from an abort */ @@ -837,6 +837,8 @@ static parser_state_t initParser(Term opts, FEnv *fe, REnv *re, int inp_stream, LOCAL_ErrorMessage = NULL; fe->old_TR = TR; LOCAL_Error_TYPE = YAP_NO_ERROR; + __android_log_print(ANDROID_LOG_INFO, "YAPDroid ", " open %s, %d", + CurrentModule == 0? "prolog": RepAtom(AtomOfTerm(CurrentModule))->StrOfAE, inp_stream); LOCAL_SourceFileName = GLOBAL_Stream[inp_stream].name; LOCAL_eot_before_eof = false; fe->tpos = StreamPosition(inp_stream); @@ -869,11 +871,11 @@ static parser_state_t initParser(Term opts, FEnv *fe, REnv *re, int inp_stream, static parser_state_t scan(REnv *re, FEnv *fe, int sno) { CACHE_REGS - /* preserve value of H after scanning: otherwise we may lose strings - and floats */ - LOCAL_tokptr = LOCAL_toktide = + /* preserve value of H after scanning: otherwise we may lose strings + and floats */ + LOCAL_tokptr = LOCAL_toktide = - Yap_tokenizer(GLOBAL_Stream + sno, false, &fe->tpos); + Yap_tokenizer(GLOBAL_Stream + sno, false, &fe->tpos); #if DEBUG if (GLOBAL_Option[2]) { TokEntry *t = LOCAL_tokptr; @@ -900,7 +902,7 @@ static parser_state_t scan(REnv *re, FEnv *fe, int sno) { static parser_state_t scanError(REnv *re, FEnv *fe, int inp_stream) { CACHE_REGS - fe->t = 0; + fe->t = 0; // running out of memory if (LOCAL_Error_TYPE == RESOURCE_ERROR_TRAIL) { LOCAL_Error_TYPE = YAP_NO_ERROR; @@ -943,7 +945,7 @@ static parser_state_t scanError(REnv *re, FEnv *fe, int inp_stream) { static parser_state_t parseError(REnv *re, FEnv *fe, int inp_stream) { CACHE_REGS - fe->t = 0; + fe->t = 0; if (LOCAL_Error_TYPE != SYNTAX_ERROR && LOCAL_Error_TYPE != YAP_NO_ERROR) { return YAP_SCANNING_ERROR; } @@ -972,7 +974,7 @@ static parser_state_t parseError(REnv *re, FEnv *fe, int inp_stream) { static parser_state_t parse(REnv *re, FEnv *fe, int inp_stream) { CACHE_REGS - TokEntry *tokstart = LOCAL_tokptr; + TokEntry *tokstart = LOCAL_tokptr; fe->t = Yap_Parse(re->prio, fe->enc, fe->cmod); fe->toklast = LOCAL_tokptr; LOCAL_tokptr = tokstart; @@ -1008,8 +1010,7 @@ Term Yap_read_term(int sno, Term opts, bool clause) { #endif yap_error_descriptor_t *new = malloc(sizeof *new); - - bool err = Yap_pushErrorContext(true, new); + bool err = Yap_pushErrorContext(true, new); int lvl = push_text_stack(); parser_state_t state = YAP_START_PARSING; while (true) { @@ -1036,7 +1037,7 @@ Term Yap_read_term(int sno, Term opts, bool clause) { break; case YAP_PARSING_FINISHED: { CACHE_REGS - bool done; + bool done; if (fe.reading_clause) done = complete_clause_processing(&fe, LOCAL_tokptr); else @@ -1051,9 +1052,6 @@ Term Yap_read_term(int sno, Term opts, bool clause) { #endif /* EMACS */ pop_text_stack(lvl); Yap_popErrorContext(err, true); - if (LOCAL_Error_TYPE != YAP_NO_ERROR) { - Yap_Error(LOCAL_Error_TYPE, Yap_MkStream(sno), LOCAL_ErrorMessage); - } return fe.t; } } @@ -1064,13 +1062,13 @@ Term Yap_read_term(int sno, Term opts, bool clause) { } static Int - read_term2(USES_REGS1) { /* '$read'(+Flag,?Term,?Module,?Vars,-Pos,-Err) */ +read_term2(USES_REGS1) { /* '$read'(+Flag,?Term,?Module,?Vars,-Pos,-Err) */ return Yap_read_term(LOCAL_c_input_stream, add_output(ARG1, ARG2), false) != - 0; + 0; } static Int read_term( - USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ + USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ int sno; Term out; @@ -1085,25 +1083,25 @@ static Int read_term( return out != 0L; } -#define READ_CLAUSE_DEFS() \ - PAR("comments", list_filler, READ_CLAUSE_COMMENTS) \ - , PAR("module", isatom, READ_CLAUSE_MODULE), \ - PAR("variable_names", filler, READ_CLAUSE_VARIABLE_NAMES), \ - PAR("variables", filler, READ_CLAUSE_VARIABLES), \ - PAR("term_position", filler, READ_CLAUSE_TERM_POSITION), \ - PAR("syntax_errors", isatom, READ_CLAUSE_SYNTAX_ERRORS), \ - PAR("output", isatom, READ_CLAUSE_OUTPUT), \ - PAR(NULL, ok, READ_CLAUSE_END) +#define READ_CLAUSE_DEFS() \ + PAR("comments", list_filler, READ_CLAUSE_COMMENTS) \ + , PAR("module", isatom, READ_CLAUSE_MODULE), \ + PAR("variable_names", filler, READ_CLAUSE_VARIABLE_NAMES), \ + PAR("variables", filler, READ_CLAUSE_VARIABLES), \ + PAR("term_position", filler, READ_CLAUSE_TERM_POSITION), \ + PAR("syntax_errors", isatom, READ_CLAUSE_SYNTAX_ERRORS), \ + PAR("output", isatom, READ_CLAUSE_OUTPUT), \ + PAR(NULL, ok, READ_CLAUSE_END) #define PAR(x, y, z) z typedef enum read_clause_enum_choices { - READ_CLAUSE_DEFS() + READ_CLAUSE_DEFS() } read_clause_choices_t; #undef PAR -#define PAR(x, y, z) \ +#define PAR(x, y, z) \ { x, y, z } static const param_t read_clause_defs[] = {READ_CLAUSE_DEFS()}; @@ -1112,8 +1110,8 @@ static const param_t read_clause_defs[] = {READ_CLAUSE_DEFS()}; static xarg *setClauseReadEnv(Term opts, FEnv *fe, struct renv *re, int sno) { CACHE_REGS - xarg *args = Yap_ArgListToVector(opts, read_clause_defs, READ_CLAUSE_END, - DOMAIN_ERROR_READ_OPTION); + xarg *args = Yap_ArgListToVector(opts, read_clause_defs, READ_CLAUSE_END, + DOMAIN_ERROR_READ_OPTION); if (args == NULL) { return NULL; } @@ -1209,7 +1207,7 @@ static Int read_clause2(USES_REGS1) { * + The `singletons` option is set from the single var flag */ static Int read_clause( - USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ + USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ int sno; Term out; @@ -1248,358 +1246,360 @@ static Int start_mega(USES_REGS1) { /* preserve value of H after scanning: otherwise we may lose strings and floats */ LOCAL_tokptr = LOCAL_toktide = - x Yap_tokenizer(GLOBAL_Stream + sno, false, &tpos); + x Yap_tokenizer(GLOBAL_Stream + sno, false, &tpos); if (tokptr->Tok == Name_tok && (next = tokptr->TokNext) != NULL && next->Tok == Ponctuation_tok && next->TokInfo == TermOpenBracket) { - bool start = true; - while((tokptr = next->TokNext)) { + bool start = true; + while((tokptr = next->TokNext)) { - if (IsAtomOrIntTerm(t=*tp)) { - ip->opc = Yap_opcode(get_atom); - ip->y_u.x_c.c = t. - ip->y_u.x_c.x = tp++; /() c */ - } else if (IsAtomOrIntTerm(t=*tp)) { - (IsAtom(tok->Tokt)||IsIntTerm(XREGS+(i+1)))extra[arity] - ] -} + if (IsAtomOrIntTerm(t=*tp)) { + ip->opc = Yap_opcode(get_atom); + ip->y_u.x_c.c = t. + ip->y_u.x_c.x = tp++; /() c */ + } else if (IsAtomOrIntTerm(t=*tp)) { + (IsAtom(tok->Tokt)||IsIntTerm(XREGS+(i+1)))extra[arity] + ] + } #endif -/** - * @pred source_location( - _File_ , _Line_ ) - * - * unify _File_ and _Line_ wuth the position of the last term read, if the - *term - * comes from a stream created by opening a file-system path with open/3 and - *friends.>position - * It ignores user_input or - * sockets. - * - * @param - _File_ - * @param - _Line_ - * - * - * - * @note SWI-Prolog built-in. - */ -static Int source_location(USES_REGS1) { - return Yap_unify(ARG1, MkAtomTerm(LOCAL_SourceFileName)) && - Yap_unify(ARG2, MkIntegerTerm(LOCAL_SourceFileLineno)); -} - -/** - * @pred read(+ Stream, -Term ) is iso - * - * Reads term _T_ from the stream _S_ instead of from the current input - * stream. - * - * @param - _Stream_ - * @param - _Term_ - * - */ -static Int read2( - USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ - int sno; - Int out; - - /* needs to change LOCAL_output_stream for write */ - sno = Yap_CheckTextStream(ARG1, Input_Stream_f, "read/3"); - if (sno == -1) { - return (FALSE); - } - out = Yap_read_term(sno, add_output(ARG2, TermNil), false); - UNLOCK(GLOBAL_Stream[sno].streamlock); - return out; -} - -/** @pred read(- T) is iso - -Reads the next term from the current input stream, and unifies it with -_T_. The term must be followed by a dot (`.`) and any blank-character -as previously defined. The syntax of the term must match the current -declarations for operators (see op). If the end-of-stream is reached, -_T_ is unified with the atom `end_of_file`. Further reads from of -the same stream may cause an error failure (see open/3). - -*/ -static Int read1( - USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ - Term out = Yap_read_term(LOCAL_c_input_stream, add_output(ARG1, TermNil), 1); - return out; -} - -/** @pred fileerrors - -Switches on the file_errors flag so that in certain error conditions -Input/Output predicates will produce an appropriated message and abort. - -*/ -static Int fileerrors(USES_REGS1) { - return setYapFlag(TermFileErrors, TermTrue); -} - -/** - @pred nofileerrors - - Switches off the `file_errors` flag, so that the predicates see/1, - tell/1, open/3 and close/1 just fail, instead of producing - an error message and aborting whenever the specified file cannot be - opened or closed. - -*/ -static Int nofileerrors( - USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ - return setYapFlag(TermFileerrors, TermFalse); -} - -static Int style_checker(USES_REGS1) { - Term t = Deref(ARG1); - - if (IsVarTerm(t)) { - Term t = TermNil; - if (getYapFlag(MkAtomTerm(AtomSingleVarWarnings)) == TermTrue) { - t = MkPairTerm(MkAtomTerm(AtomSingleVarWarnings), t); + /** + * @pred source_location( - _File_ , _Line_ ) + * + * unify _File_ and _Line_ wuth the position of the last term read, if the + *term + * comes from a stream created by opening a file-system path with open/3 and + *friends.>position + * It ignores user_input or + * sockets. + * + * @param - _File_ + * @param - _Line_ + * + * + * + * @note SWI-Prolog built-in. + */ + static Int source_location(USES_REGS1) { + return Yap_unify(ARG1, MkAtomTerm(LOCAL_SourceFileName)) && + Yap_unify(ARG2, MkIntegerTerm(LOCAL_SourceFileLineno)); } - if (getYapFlag(MkAtomTerm(AtomDiscontiguousWarnings)) == TermTrue) { - t = MkPairTerm(MkAtomTerm(AtomDiscontiguousWarnings), t); - } - if (getYapFlag(MkAtomTerm(AtomRedefineWarnings)) == TermTrue) { - t = MkPairTerm(MkAtomTerm(AtomRedefineWarnings), t); - } - } else { - while (IsPairTerm(t)) { - Term h = HeadOfTerm(t); - t = TailOfTerm(t); - if (IsVarTerm(h)) { - Yap_Error(INSTANTIATION_ERROR, t, "style_check/1"); - return (FALSE); - } else if (IsAtomTerm(h)) { - Atom at = AtomOfTerm(h); - if (at == AtomSingleVarWarnings) - setYapFlag(MkAtomTerm(AtomSingleVarWarnings), TermTrue); - else if (at == AtomDiscontiguousWarnings) - setYapFlag(MkAtomTerm(AtomDiscontiguousWarnings), TermTrue); - else if (at == AtomRedefineWarnings) - setYapFlag(MkAtomTerm(AtomRedefineWarnings), TermTrue); + /** + * @pred read(+ Stream, -Term ) is iso + * + * Reads term _T_ from the stream _S_ instead of from the current input + * stream. + * + * @param - _Stream_ + * @param - _Term_ + * + */ + static Int read2( + USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ + int sno; + Int out; + + /* needs to change LOCAL_output_stream for write */ + sno = Yap_CheckTextStream(ARG1, Input_Stream_f, "read/3"); + if (sno == -1) { + return (FALSE); + } + out = Yap_read_term(sno, add_output(ARG2, TermNil), false); + UNLOCK(GLOBAL_Stream[sno].streamlock); + return out; + } + + /** @pred read(- T) is iso + + Reads the next term from the current input stream, and unifies it with + _T_. The term must be followed by a dot (`.`) and any blank-character + as previously defined. The syntax of the term must match the current + declarations for operators (see op). If the end-of-stream is reached, + _T_ is unified with the atom `end_of_file`. Further reads from of + the same stream may cause an error failure (see open/3). + + */ + static Int read1( + USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ + Term out = Yap_read_term(LOCAL_c_input_stream, add_output(ARG1, TermNil), 1); + return out; + } + + /** @pred fileerrors + + Switches on the file_errors flag so that in certain error conditions + Input/Output predicates will produce an appropriated message and abort. + + */ + static Int fileerrors(USES_REGS1) { + return setYapFlag(TermFileErrors, TermTrue); + } + + /** + @pred nofileerrors + + Switches off the `file_errors` flag, so that the predicates see/1, + tell/1, open/3 and close/1 just fail, instead of producing + an error message and aborting whenever the specified file cannot be + opened or closed. + + */ + static Int nofileerrors( + USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ + return setYapFlag(TermFileerrors, TermFalse); + } + + static Int style_checker(USES_REGS1) { + Term t = Deref(ARG1); + + if (IsVarTerm(t)) { + Term t = TermNil; + if (getYapFlag(MkAtomTerm(AtomSingleVarWarnings)) == TermTrue) { + t = MkPairTerm(MkAtomTerm(AtomSingleVarWarnings), t); + } + if (getYapFlag(MkAtomTerm(AtomDiscontiguousWarnings)) == TermTrue) { + t = MkPairTerm(MkAtomTerm(AtomDiscontiguousWarnings), t); + } + if (getYapFlag(MkAtomTerm(AtomRedefineWarnings)) == TermTrue) { + t = MkPairTerm(MkAtomTerm(AtomRedefineWarnings), t); + } } else { - Atom at = AtomOfTerm(ArgOfTerm(1, h)); - if (at == AtomSingleVarWarnings) - setYapFlag(MkAtomTerm(AtomSingleVarWarnings), TermFalse); - else if (at == AtomDiscontiguousWarnings) - setYapFlag(MkAtomTerm(AtomDiscontiguousWarnings), TermFalse); - else if (at == AtomRedefineWarnings) - setYapFlag(MkAtomTerm(AtomRedefineWarnings), TermFalse); + while (IsPairTerm(t)) { + Term h = HeadOfTerm(t); + t = TailOfTerm(t); + + if (IsVarTerm(h)) { + Yap_Error(INSTANTIATION_ERROR, t, "style_check/1"); + return (FALSE); + } else if (IsAtomTerm(h)) { + Atom at = AtomOfTerm(h); + if (at == AtomSingleVarWarnings) + setYapFlag(MkAtomTerm(AtomSingleVarWarnings), TermTrue); + else if (at == AtomDiscontiguousWarnings) + setYapFlag(MkAtomTerm(AtomDiscontiguousWarnings), TermTrue); + else if (at == AtomRedefineWarnings) + setYapFlag(MkAtomTerm(AtomRedefineWarnings), TermTrue); + } else { + Atom at = AtomOfTerm(ArgOfTerm(1, h)); + if (at == AtomSingleVarWarnings) + setYapFlag(MkAtomTerm(AtomSingleVarWarnings), TermFalse); + else if (at == AtomDiscontiguousWarnings) + setYapFlag(MkAtomTerm(AtomDiscontiguousWarnings), TermFalse); + else if (at == AtomRedefineWarnings) + setYapFlag(MkAtomTerm(AtomRedefineWarnings), TermFalse); + } + } + } + return TRUE; + } + + Term Yap_BufferToTerm(const char *s, Term opts) { + Term rval; + int sno; + encoding_t l = ENC_ISO_UTF8; + sno = Yap_open_buf_read_stream((char *)s, strlen(s)+1, &l, + MEM_BUF_USER, Yap_LookupAtom(Yap_StrPrefix(s,16)), TermNone ); + + GLOBAL_Stream[sno].status |= CloseOnException_Stream_f; + rval = Yap_read_term(sno, opts, false); + Yap_CloseStream(sno); + return rval; + } + + Term Yap_UBufferToTerm(const unsigned char *s, Term opts) { + Term rval; + int sno; + encoding_t l = ENC_ISO_UTF8; + sno = Yap_open_buf_read_stream((char *)s, strlen((const char *)s), &l, + MEM_BUF_USER, Yap_LookupAtom(Yap_StrPrefix((char *)s,16)), TermNone); + GLOBAL_Stream[sno].status |= CloseOnException_Stream_f; + rval = Yap_read_term(sno, opts, false); + Yap_CloseStream(sno); + return rval; + } + + X_API Term Yap_BufferToTermWithPrioBindings(const char *s, Term opts, + Term bindings, size_t len, + int prio) { + CACHE_REGS + Term ctl; + + ctl = opts; + if (bindings) { + ctl = add_names(bindings, TermNil); + } + if (prio != 1200) { + ctl = add_priority(bindings, ctl); + } + return Yap_BufferToTerm(s, ctl); + } + + /** + * @pred read_term_from_atom( +Atom , -T , +Options ) + * + * read a term _T_ stored in constant _Atom_ according to _Options_ + * + * @param _Atom_ the source _Atom_ + * @param _T_ the output term _T_, may be any term + * @param _Options_ read_term/3 options. + * + * @note Originally from SWI-Prolog, in YAP only works with internalised + *atoms + * Check read_term_from_atomic/3 for the general version. Also, the built-in + *is + *supposed to + * use YAP's internal encoding, so please avoid the encoding/1 option. + */ + static Int read_term_from_atom(USES_REGS1) { + Term t1 = Deref(ARG1); + Atom at; + const unsigned char *s; + + if (IsVarTerm(t1)) { + Yap_Error(INSTANTIATION_ERROR, t1, "style_check/1"); + return false; + } else if (!IsAtomTerm(t1)) { + Yap_Error(TYPE_ERROR_ATOM, t1, "style_check/1"); + return false; + } else { + at = AtomOfTerm(t1); + s = at->UStrOfAE; + } + Term ctl = add_output(ARG2, ARG3); + + return Yap_UBufferToTerm(s, ctl); + } + + /** + * @pred read_term_from_atomic( +Atomic , - T , +Options ) + * + * read a term _T_ stored in text _Atomic_ according to _Options_ + * + * @param _Atomic_ the source may be an atom, string, list of codes, or list + *of + *chars. + * @param _T_ the output term _T_, may be any term + * @param _Options_ read_term/3 options. + * + * @notes Idea originally from SWI-Prolog, but in YAP we separate atomic and + *atom. + * Encoding is fixed in atoms and strings. + */ + static Int read_term_from_atomic(USES_REGS1) { + Term t1 = Deref(ARG1); + const unsigned char *s; + + if (IsVarTerm(t1)) { + Yap_Error(INSTANTIATION_ERROR, t1, "read_term_from_atomic/3"); + return (FALSE); + } else if (!IsAtomicTerm(t1)) { + Yap_Error(TYPE_ERROR_ATOMIC, t1, "read_term_from_atomic/3"); + return (FALSE); + } else { + Term t = Yap_AtomicToString(t1 PASS_REGS); + s = UStringOfTerm(t); + } + Term ctl = add_output(ARG2, ARG3); + + return Yap_UBufferToTerm(s, ctl); + } + + /** + * @pred read_term_from_string( +String , - T , + Options ) + * + * read a term _T_ stored in constant _String_ according to _Options_ + * + * @param _String_ the source _String_ + * @param _T_ the output term _T_, may be any term + * @param _Options_ read_term/3 options. + * + * Idea from SWI-Prolog, in YAP only works with strings + * Check read_term_from_atomic/3 for the general version. + */ + static Int read_term_from_string(USES_REGS1) { + Term t1 = Deref(ARG1), rc; + const unsigned char *s; + size_t len; + BACKUP_H() + if (IsVarTerm(t1)) { + Yap_Error(INSTANTIATION_ERROR, t1, "read_term_from_string/3"); + return (FALSE); + } else if (!IsStringTerm(t1)) { + Yap_Error(TYPE_ERROR_STRING, t1, "read_term_from_string/3"); + return (FALSE); + } else { + s = UStringOfTerm(t1); + len = strlen_utf8(s); + } + char *ss = (char *)s; + encoding_t enc = ENC_ISO_UTF8; + int sno = Yap_open_buf_read_stream(ss, len, &enc, MEM_BUF_USER, Yap_LookupAtom(Yap_StrPrefix(ss,16)), TermString); + GLOBAL_Stream[sno].status |= CloseOnException_Stream_f; + rc = Yap_read_term(sno, Deref(ARG3), 3); + Yap_CloseStream(sno); + RECOVER_H(); + if (!rc) + return false; + return Yap_unify(rc, ARG2); + } + + static Int atomic_to_term(USES_REGS1) { + Term t1 = Deref(ARG1); + int l = push_text_stack(); + const unsigned char *s = Yap_TextToUTF8Buffer(t1 PASS_REGS); + Int rc = Yap_UBufferToTerm(s, add_output(ARG2, add_names(ARG3, TermNil))); + pop_text_stack(l); + return rc; + } + + static Int atom_to_term(USES_REGS1) { + Term t1 = Deref(ARG1); + if (IsVarTerm(t1)) { + Yap_Error(INSTANTIATION_ERROR, t1, "read_term_from_string/3"); + return (FALSE); + } else if (!IsAtomTerm(t1)) { + Yap_Error(TYPE_ERROR_ATOM, t1, "read_term_from_atomic/3"); + return (FALSE); + } else { + Term t = Yap_AtomicToString(t1 PASS_REGS); + const unsigned char *us = UStringOfTerm(t); + return Yap_UBufferToTerm(us, add_output(ARG2, add_names(ARG3, TermNil))); } } - } - return TRUE; -} -Term Yap_BufferToTerm(const char *s, Term opts) { - Term rval; - int sno; - encoding_t l = ENC_ISO_UTF8; - sno = Yap_open_buf_read_stream((char *)s, strlen((const char *)s)+1, &l, - MEM_BUF_USER); + static Int string_to_term(USES_REGS1) { + Term t1 = Deref(ARG1); - GLOBAL_Stream[sno].status |= CloseOnException_Stream_f; - rval = Yap_read_term(sno, opts, false); - Yap_CloseStream(sno); - return rval; -} + if (IsVarTerm(t1)) { + Yap_Error(INSTANTIATION_ERROR, t1, "read_term_from_string/3"); + return (FALSE); + } else if (!IsStringTerm(t1)) { + Yap_Error(TYPE_ERROR_STRING, t1, "read_term_from_string/3"); + return (FALSE); + } else { + const unsigned char *us = UStringOfTerm(t1); + return Yap_UBufferToTerm(us, add_output(ARG2, add_names(ARG3, TermNil))); + } + } -Term Yap_UBufferToTerm(const unsigned char *s, Term opts) { - Term rval; - int sno; - encoding_t l = ENC_ISO_UTF8; - sno = Yap_open_buf_read_stream((char *)s, strlen((const char *)s), &l, - MEM_BUF_USER); - GLOBAL_Stream[sno].status |= CloseOnException_Stream_f; - rval = Yap_read_term(sno, opts, false); - Yap_CloseStream(sno); - return rval; -} + void Yap_InitReadTPreds(void) { + Yap_InitCPred("read_term", 2, read_term2, SyncPredFlag); + Yap_InitCPred("read_term", 3, read_term, SyncPredFlag); -X_API Term Yap_BufferToTermWithPrioBindings(const char *s, Term opts, - Term bindings, size_t len, - int prio) { - CACHE_REGS - Term ctl; + Yap_InitCPred("scan_to_list", 2, scan_to_list, SyncPredFlag); + Yap_InitCPred("read", 1, read1, SyncPredFlag); + Yap_InitCPred("read", 2, read2, SyncPredFlag); + Yap_InitCPred("read_clause", 2, read_clause2, SyncPredFlag); + Yap_InitCPred("read_clause", 3, read_clause, 0); + Yap_InitCPred("read_term_from_atom", 3, read_term_from_atom, 0); + Yap_InitCPred("read_term_from_atomic", 3, read_term_from_atomic, 0); + Yap_InitCPred("read_term_from_string", 3, read_term_from_string, 0); + Yap_InitCPred("atom_to_term", 3, atom_to_term, 0); + Yap_InitCPred("atomic_to_term", 3, atomic_to_term, 0); + Yap_InitCPred("string_to_term", 3, string_to_term, 0); - ctl = opts; - if (bindings) { - ctl = add_names(bindings, TermNil); - } - if (prio != 1200) { - ctl = add_priority(bindings, ctl); - } - return Yap_BufferToTerm(s, ctl); -} - -/** - * @pred read_term_from_atom( +Atom , -T , +Options ) - * - * read a term _T_ stored in constant _Atom_ according to _Options_ - * - * @param _Atom_ the source _Atom_ - * @param _T_ the output term _T_, may be any term - * @param _Options_ read_term/3 options. - * - * @note Originally from SWI-Prolog, in YAP only works with internalised - *atoms - * Check read_term_from_atomic/3 for the general version. Also, the built-in - *is - *supposed to - * use YAP's internal encoding, so please avoid the encoding/1 option. - */ -static Int read_term_from_atom(USES_REGS1) { - Term t1 = Deref(ARG1); - Atom at; - const unsigned char *s; - - if (IsVarTerm(t1)) { - Yap_Error(INSTANTIATION_ERROR, t1, "style_check/1"); - return false; - } else if (!IsAtomTerm(t1)) { - Yap_Error(TYPE_ERROR_ATOM, t1, "style_check/1"); - return false; - } else { - at = AtomOfTerm(t1); - s = at->UStrOfAE; - } - Term ctl = add_output(ARG2, ARG3); - - return Yap_UBufferToTerm(s, ctl); -} - -/** - * @pred read_term_from_atomic( +Atomic , - T , +Options ) - * - * read a term _T_ stored in text _Atomic_ according to _Options_ - * - * @param _Atomic_ the source may be an atom, string, list of codes, or list - *of - *chars. - * @param _T_ the output term _T_, may be any term - * @param _Options_ read_term/3 options. - * - * @notes Idea originally from SWI-Prolog, but in YAP we separate atomic and - *atom. - * Encoding is fixed in atoms and strings. - */ -static Int read_term_from_atomic(USES_REGS1) { - Term t1 = Deref(ARG1); - const unsigned char *s; - - if (IsVarTerm(t1)) { - Yap_Error(INSTANTIATION_ERROR, t1, "read_term_from_atomic/3"); - return (FALSE); - } else if (!IsAtomicTerm(t1)) { - Yap_Error(TYPE_ERROR_ATOMIC, t1, "read_term_from_atomic/3"); - return (FALSE); - } else { - Term t = Yap_AtomicToString(t1 PASS_REGS); - s = UStringOfTerm(t); - } - Term ctl = add_output(ARG2, ARG3); - - return Yap_UBufferToTerm(s, ctl); -} - -/** - * @pred read_term_from_string( +String , - T , + Options ) - * - * read a term _T_ stored in constant _String_ according to _Options_ - * - * @param _String_ the source _String_ - * @param _T_ the output term _T_, may be any term - * @param _Options_ read_term/3 options. - * - * Idea from SWI-Prolog, in YAP only works with strings - * Check read_term_from_atomic/3 for the general version. - */ -static Int read_term_from_string(USES_REGS1) { - Term t1 = Deref(ARG1), rc; - const unsigned char *s; - size_t len; - if (IsVarTerm(t1)) { - Yap_Error(INSTANTIATION_ERROR, t1, "read_term_from_string/3"); - return (FALSE); - } else if (!IsStringTerm(t1)) { - Yap_Error(TYPE_ERROR_STRING, t1, "read_term_from_string/3"); - return (FALSE); - } else { - s = UStringOfTerm(t1); - len = strlen_utf8(s); - } - char *ss = (char *)s; - encoding_t enc = ENC_ISO_UTF8; - int sno = Yap_open_buf_read_stream(ss, len, &enc, MEM_BUF_USER); - GLOBAL_Stream[sno].status |= CloseOnException_Stream_f; - rc = Yap_read_term(sno, Deref(ARG3), 3); - Yap_CloseStream(sno); - if (!rc) - return false; - return Yap_unify(rc, ARG2); -} - -static Int atomic_to_term(USES_REGS1) { - Term t1 = Deref(ARG1); - int l = push_text_stack(); - const unsigned char *s = Yap_TextToUTF8Buffer(t1 PASS_REGS); - Int rc = Yap_UBufferToTerm(s, add_output(ARG2, add_names(ARG3, TermNil))); - pop_text_stack(l); - return rc; -} - -static Int atom_to_term(USES_REGS1) { - Term t1 = Deref(ARG1); - if (IsVarTerm(t1)) { - Yap_Error(INSTANTIATION_ERROR, t1, "read_term_from_string/3"); - return (FALSE); - } else if (!IsAtomTerm(t1)) { - Yap_Error(TYPE_ERROR_ATOM, t1, "read_term_from_atomic/3"); - return (FALSE); - } else { - Term t = Yap_AtomicToString(t1 PASS_REGS); - const unsigned char *us = UStringOfTerm(t); - return Yap_UBufferToTerm(us, add_output(ARG2, add_names(ARG3, TermNil))); - } -} - -static Int string_to_term(USES_REGS1) { - Term t1 = Deref(ARG1); - - if (IsVarTerm(t1)) { - Yap_Error(INSTANTIATION_ERROR, t1, "read_term_from_string/3"); - return (FALSE); - } else if (!IsStringTerm(t1)) { - Yap_Error(TYPE_ERROR_STRING, t1, "read_term_from_string/3"); - return (FALSE); - } else { - const unsigned char *us = UStringOfTerm(t1); - return Yap_UBufferToTerm(us, add_output(ARG2, add_names(ARG3, TermNil))); - } -} - -void Yap_InitReadTPreds(void) { - Yap_InitCPred("read_term", 2, read_term2, SyncPredFlag); - Yap_InitCPred("read_term", 3, read_term, SyncPredFlag); - - Yap_InitCPred("scan_to_list", 2, scan_to_list, SyncPredFlag); - Yap_InitCPred("read", 1, read1, SyncPredFlag); - Yap_InitCPred("read", 2, read2, SyncPredFlag); - Yap_InitCPred("read_clause", 2, read_clause2, SyncPredFlag); - Yap_InitCPred("read_clause", 3, read_clause, 0); - Yap_InitCPred("read_term_from_atom", 3, read_term_from_atom, 0); - Yap_InitCPred("read_term_from_atomic", 3, read_term_from_atomic, 0); - Yap_InitCPred("read_term_from_string", 3, read_term_from_string, 0); - Yap_InitCPred("atom_to_term", 3, atom_to_term, 0); - Yap_InitCPred("atomic_to_term", 3, atomic_to_term, 0); - Yap_InitCPred("string_to_term", 3, string_to_term, 0); - - Yap_InitCPred("fileerrors", 0, fileerrors, SyncPredFlag); - Yap_InitCPred("nofileeleerrors", 0, nofileerrors, SyncPredFlag); - Yap_InitCPred("source_location", 2, source_location, SyncPredFlag); - Yap_InitCPred("$style_checker", 1, style_checker, - SyncPredFlag | HiddenPredFlag); -} + Yap_InitCPred("fileerrors", 0, fileerrors, SyncPredFlag); + Yap_InitCPred("nofileeleerrors", 0, nofileerrors, SyncPredFlag); + Yap_InitCPred("source_location", 2, source_location, SyncPredFlag); + Yap_InitCPred("$style_checker", 1, style_checker, + SyncPredFlag | HiddenPredFlag); + } diff --git a/os/streams.c b/os/streams.c index 0286ee460..8e5baa2bc 100644 --- a/os/streams.c +++ b/os/streams.c @@ -683,7 +683,7 @@ static xarg *generate_property(int sno, Term t2, } static Int cont_stream_property(USES_REGS1) { /* current_stream */ - bool det; + bool det = false; xarg *args; int i = IntOfTerm(EXTRA_CBACK_ARG(2, 1)); stream_property_choices_t p = STREAM_PROPERTY_END; @@ -705,7 +705,7 @@ static Int cont_stream_property(USES_REGS1) { /* current_stream */ if (LOCAL_Error_TYPE != YAP_NO_ERROR) { if (LOCAL_Error_TYPE == DOMAIN_ERROR_GENERIC_ARGUMENT) LOCAL_Error_TYPE = DOMAIN_ERROR_STREAM_PROPERTY_OPTION; - Yap_Error(LOCAL_Error_TYPE, t2, NULL); + Yap_ThrowError(LOCAL_Error_TYPE, t2, NULL); return false; } cut_fail(); @@ -714,16 +714,17 @@ static Int cont_stream_property(USES_REGS1) { /* current_stream */ if (IsAtomTerm(args[STREAM_PROPERTY_ALIAS].tvalue)) { // one solution only i = Yap_CheckAlias(AtomOfTerm(args[STREAM_PROPERTY_ALIAS].tvalue)); - free(args) UNLOCK(GLOBAL_Stream[i].streamlock); + UNLOCK(GLOBAL_Stream[i].streamlock); if (i < 0 || !Yap_unify(ARG1, Yap_MkStream(i))) { + free(args); cut_fail(); } - cut_succeed(); + det = true; } LOCK(GLOBAL_Stream[i].streamlock); rc = do_stream_property(i, args PASS_REGS); UNLOCK(GLOBAL_Stream[i].streamlock); - if (IsVarTerm(t1)) { + if (!det && IsVarTerm(t1)) { if (rc) rc = Yap_unify(ARG1, Yap_MkStream(i)); if (p == STREAM_PROPERTY_END) { @@ -743,7 +744,7 @@ static Int cont_stream_property(USES_REGS1) { /* current_stream */ } } else { // done - det = (p == STREAM_PROPERTY_END); + det = det || (p == STREAM_PROPERTY_END); } free(args); if (rc) { @@ -998,7 +999,8 @@ static void CloseStream(int sno) { // __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "close stream <%d>", // sno); VFS_t *me; - if ((me = GLOBAL_Stream[sno].vfs) != NULL && + //fprintf( stderr, "- %d\n",sno); +if ((me = GLOBAL_Stream[sno].vfs) != NULL && GLOBAL_Stream[sno].file == NULL) { if (me->close) { me->close(sno); diff --git a/os/writeterm.c b/os/writeterm.c index 24e92bd67..c4586f8ec 100644 --- a/os/writeterm.c +++ b/os/writeterm.c @@ -93,7 +93,7 @@ static Term readFromBuffer(const char *s, Term opts) { int sno; encoding_t enc = ENC_ISO_UTF8; sno = Yap_open_buf_read_stream((char *)s, strlen_utf8((unsigned char *)s), - &enc, MEM_BUF_USER); + &enc, MEM_BUF_USER, Yap_LookupAtom(Yap_StrPrefix((char *)s,16)), TermNone); rval = Yap_read_term(sno, opts, 3); Yap_CloseStream(sno); @@ -672,7 +672,7 @@ static Int term_to_string(USES_REGS1) { Term t2 = Deref(ARG2), rc = false, t1 = Deref(ARG1); const char *s; if (IsVarTerm(t2)) { - s = Yap_TermToBuffer(ARG1, LOCAL_encoding, Quote_illegal_f | Handle_vars_f); + s = Yap_TermToBuffer(t1, Quote_illegal_f | Handle_vars_f); if (!s || !MkStringTerm(s)) { Yap_Error(RESOURCE_ERROR_HEAP, t1, "Could not get memory from the operating system"); @@ -692,7 +692,7 @@ static Int term_to_atom(USES_REGS1) { Term t2 = Deref(ARG2), ctl, rc = false; Atom at; if (IsVarTerm(t2)) { - const char *s = Yap_TermToBuffer(Deref(ARG1), LOCAL_encoding, + const char *s = Yap_TermToBuffer(Deref(ARG1), Quote_illegal_f | Handle_vars_f); if (!s || !(at = Yap_UTF8ToAtom((const unsigned char *)s))) { Yap_Error(RESOURCE_ERROR_HEAP, t2, @@ -711,6 +711,25 @@ static Int term_to_atom(USES_REGS1) { Yap_unify(rc, ARG1); } +char *Yap_TermToBuffer(Term t, int flags) { + CACHE_REGS + int sno = Yap_open_buf_write_stream(LOCAL_encoding,flags); + + if (sno < 0) + return NULL; + if (t == 0) + return NULL; + else + t = Deref(t); + GLOBAL_Stream[sno].encoding = LOCAL_encoding; + GLOBAL_Stream[sno].status |= CloseOnException_Stream_f; + Yap_plwrite(t, GLOBAL_Stream + sno, 0, flags, GLOBAL_MaxPriority); + + char *new = Yap_MemExportStreamPtr(sno); + Yap_CloseStream(sno); + return new; +} + void Yap_InitWriteTPreds(void) { Yap_InitCPred("write_term", 2, write_term2, SyncPredFlag); Yap_InitCPred("write_term", 3, write_term3, SyncPredFlag); diff --git a/os/yapio.h b/os/yapio.h index 7fb6d4fbf..76ee6f0bb 100644 --- a/os/yapio.h +++ b/os/yapio.h @@ -89,7 +89,7 @@ extern int Yap_GetCharForSIGINT(void); extern Int Yap_StreamToFileNo(Term); extern int Yap_OpenStream(Term tin, const char* io_mode, Term user_name, encoding_t enc); extern int Yap_FileStream(FILE*, char *, Term, int, VFS_t *); -extern char *Yap_TermToBuffer(Term t, encoding_t encoding, int flags); +extern char *Yap_TermToBuffer(Term t, int flags); extern char *Yap_HandleToString(yhandle_t l, size_t sz, size_t *length, encoding_t *encoding, int flags); extern int Yap_GetFreeStreamD(void); @@ -114,11 +114,14 @@ typedef enum mem_buf_source { extern char *Yap_MemStreamBuf(int sno); +extern char *Yap_StrPrefix( const char *buf, size_t n) ; + extern Term Yap_StringToNumberTerm(const char *s, encoding_t *encp, bool error_on); extern int Yap_FormatFloat(Float f, char **s, size_t sz); extern int Yap_open_buf_read_stream(const char *buf, size_t nchars, - encoding_t *encp, memBufSource src); + encoding_t *encp, memBufSource src, Atom name, + Term uname); extern int Yap_open_buf_write_stream(encoding_t enc, memBufSource src); extern Term Yap_BufferToTerm(const char *s, Term opts); extern X_API Term Yap_BufferToTermWithPrioBindings(const char *s, Term opts, Term bindings, size_t sz, diff --git a/os/ypsocks.c b/os/ypsocks.c index f49ac7169..b085eb8c6 100755 --- a/os/ypsocks.c +++ b/os/ypsocks.c @@ -202,7 +202,7 @@ void Yap_init_socks(char *host, long interface_port) { soadr.sin_port = htons((short)interface_port); if (he != NULL) { - memcpy((char *)&adr, (char *)he->h_addr_list[0], (size_t)he->h_length); + memmove((char *)&adr, (char *)he->h_addr_list[0], (size_t)he->h_length); } else { adr.s_addr = inet_addr(host); } @@ -635,7 +635,7 @@ static Int p_socket_bind(USES_REGS1) { #endif return (FALSE); } - memcpy((void *)&saddr.sin_addr, (void *)he->h_addr_list[0], he->h_length); + memmove((void *)&saddr.sin_addr, (void *)he->h_addr_list[0], he->h_length); } if (IsVarTerm(tport)) { port = 0; @@ -774,7 +774,7 @@ static Int p_socket_connect(USES_REGS1) { #endif return (FALSE); } - memcpy((void *)&saddr.sin_addr, (void *)he->h_addr_list[0], he->h_length); + memmove((void *)&saddr.sin_addr, (void *)he->h_addr_list[0], he->h_length); } if (IsVarTerm(tport)) { Yap_Error(INSTANTIATION_ERROR, tport, "socket_connect/3"); @@ -1239,7 +1239,7 @@ static Int p_hostname_address(USES_REGS1) { #endif return false; } - memcpy((char *)&adr, (char *)he->h_addr_list[0], (size_t)he->h_length); + memmove((char *)&adr, (char *)he->h_addr_list[0], (size_t)he->h_length); out = MkAtomTerm(Yap_LookupAtom(inet_ntoa(adr))); return (Yap_unify(out, ARG2)); } diff --git a/packages/cuda/bpredscpu.cpp b/packages/cuda/bpredscpu.cpp index a0d3309d9..50123715c 100644 --- a/packages/cuda/bpredscpu.cpp +++ b/packages/cuda/bpredscpu.cpp @@ -80,7 +80,7 @@ int bpredscpu(int *dop1, int rows, int *bin, int3 numpreds, int **ret) ptr = fres; for(x = 0; x < NUM_T; x++) { - memcpy(ptr, vec[x].data(), ini[x] * sizeof(int)); + memmove(ptr, vec[x].data(), ini[x] * sizeof(int)); ptr += ini[x]; } *ret = fres; diff --git a/packages/cuda/cuda.c b/packages/cuda/cuda.c index 0748e75b7..8aa1f83bc 100644 --- a/packages/cuda/cuda.c +++ b/packages/cuda/cuda.c @@ -376,12 +376,12 @@ load_rule( void ) { pred->is_fact = FALSE; x = (strlen(strname) + 1) * sizeof(char); pred->predname = (char *)malloc(x); - memcpy(pred->predname, strname, x); + memmove(pred->predname, strname, x); nvec = (int32_t *)malloc(sizeof(int32_t)*(ptr-vec)); - memcpy(nvec, vec, sizeof(int32_t)*(ptr-vec)); + memmove(nvec, vec, sizeof(int32_t)*(ptr-vec)); pred->address_host_table = nvec; pred->negatives = (int32_t *)malloc(sizeof(int32_t) * cont); - memcpy(pred->negatives, neg, sizeof(int32_t) * cont); + memmove(pred->negatives, neg, sizeof(int32_t) * cont); Cuda_NewRule( pred ); return YAP_Unify(YAP_ARG4, YAP_MkIntTerm((YAP_Int)pred)); } diff --git a/packages/cuda/dbio.cu b/packages/cuda/dbio.cu index 14e88a747..06b3c1ae4 100644 --- a/packages/cuda/dbio.cu +++ b/packages/cuda/dbio.cu @@ -180,7 +180,7 @@ void postgresRead(PGconn **ret, vector *L, int *inpquery, char *names, { numt = (strlen(tok) + 1) * sizeof(char); qrs[x] = (char *)malloc(numt); - memcpy(qrs[x], tok, numt); + memmove(qrs[x], tok, numt); } x += 2; } @@ -264,7 +264,7 @@ void postgresRead(PGconn **ret, vector *L, int *inpquery, char *names, L->at(z).address_host_table = mat; numc = (strlen(tok) + 1) * sizeof(char); L->at(z).predname = (char *)malloc(numc); - memcpy(L->at(z).predname, tok, numc); + memmove(L->at(z).predname, tok, numc); PQclear(pgr); tok = strtok(NULL, " "); z++; diff --git a/packages/cuda/joincpu.cpp b/packages/cuda/joincpu.cpp index ead42edb5..42658fc51 100644 --- a/packages/cuda/joincpu.cpp +++ b/packages/cuda/joincpu.cpp @@ -466,7 +466,7 @@ int joincpu(int *p1, int *p2, int rLen, int sLen, int of1, int of2, listrule_names[x+1] - rules->rule_names[x]; if(rules->address_host_table[rules->rule_names[x]] > 0) { - memcpy(rest + cont, rules->address_host_table + rules->rule_names[x], subs * sizeof(int)); + memmove(rest + cont, rules->address_host_table + rules->rule_names[x], subs * sizeof(int)); cont += subs; } else @@ -123,17 +123,17 @@ void movebpreds(InputIterator rules, InputIterator end) subs--; if(rules->address_host_table[pos] > 0 && rules->address_host_table[pos+1] > 0) { - memcpy(move2 + cont3, rules->address_host_table + rules->rule_names[x], subs * sizeof(int)); + memmove(move2 + cont3, rules->address_host_table + rules->rule_names[x], subs * sizeof(int)); cont3 += subs; } else { - memcpy(move + cont2, rules->address_host_table + rules->rule_names[x], subs * sizeof(int)); + memmove(move + cont2, rules->address_host_table + rules->rule_names[x], subs * sizeof(int)); cont2 += subs; } } } - memcpy(rules->address_host_table, rest, cont * sizeof(int)); + memmove(rules->address_host_table, rest, cont * sizeof(int)); pos = 1; for(x = 1; x <= total; x++) @@ -178,7 +178,7 @@ void movebpreds(InputIterator rules, InputIterator end) pos += 2; cont = closestpred(rules->rule_names, rules->num_rows, p1); - memcpy(rules->preds[cont] + rules->numpreds[cont].x, move + cont2, total); + memmove(rules->preds[cont] + rules->numpreds[cont].x, move + cont2, total); rules->numpreds[cont].x += 3; cont2 += 3; } @@ -212,19 +212,19 @@ void movebpreds(InputIterator rules, InputIterator end) cont2 = closestpred(rules->rule_names, rules->num_rows, p2); if(cont == cont2) { - memcpy(rules->preds[cont] + rules->numpreds[cont].x, move2 + cont3, total); + memmove(rules->preds[cont] + rules->numpreds[cont].x, move2 + cont3, total); rules->numpreds[cont].x += 3; } else { if(cont > cont2) { - memcpy(rules->preds[cont] + rules->numpreds[cont].x + rules->numpreds[cont].y, move2 + cont3, total); + memmove(rules->preds[cont] + rules->numpreds[cont].x + rules->numpreds[cont].y, move2 + cont3, total); rules->numpreds[cont].y += 3; } else { - memcpy(rules->preds[cont2] + rules->numpreds[cont2].x + rules->numpreds[cont2].y, move2 + cont3, total); + memmove(rules->preds[cont2] + rules->numpreds[cont2].x + rules->numpreds[cont2].y, move2 + cont3, total); rules->numpreds[cont2].y += 3; } } @@ -345,7 +345,7 @@ void seleccion(InputIterator actual, InputIterator end) sl = x - 1; tam = cont * sizeof(int); actual->select[sl] = (int *)malloc(tam); - memcpy(actual->select[sl], pv, tam); + memmove(actual->select[sl], pv, tam); actual->numsel[sl] = cont; } actual++; @@ -480,9 +480,9 @@ int2 columnsproject(int *first, int tam, int *rule, int ini, int fin, int sini, temp = ret.y * sizeof(int); free(*newrule); *newrule = (int *)malloc(temp); - memcpy(*newrule, pv, temp); + memmove(*newrule, pv, temp); *res = (int *)malloc(temp); - memcpy(*res, pv2, temp); + memmove(*res, pv2, temp); return ret; } @@ -509,7 +509,7 @@ int wherejoin(int *tmprule, int tmplen, int *rule, int tam2, int **res) temp = cont * sizeof(int); *res = (int *)malloc(temp); - memcpy(*res, joins, temp); + memmove(*res, joins, temp); return cont; } @@ -611,7 +611,7 @@ void proyeccion(InputIterator actual, InputIterator end) temp = pos.x * sizeof(int); actual->project[0] = (int *)malloc(temp); - memcpy(actual->project[0], fjoin, temp); + memmove(actual->project[0], fjoin, temp); pos.y = pos.x; actual->projpos[0] = pos; actual++; @@ -628,7 +628,7 @@ void proyeccion(InputIterator actual, InputIterator end) pos.y = actual->rule_names[2] - actual->rule_names[1] - 2; temp = pos.y * sizeof(int); pv = (int *)malloc(temp); - memcpy(pv, actual->address_host_table + actual->rule_names[1] + 1, temp); + memmove(pv, actual->address_host_table + actual->rule_names[1] + 1, temp); for(x = 2, y = 0; x <= numjoins; x++, y++) { @@ -676,7 +676,7 @@ void proyeccion(InputIterator actual, InputIterator end) } temp = pos.x * sizeof(int); actual->project[numjoins] = (int *)malloc(temp); - memcpy(actual->project[numjoins], fjoin, temp); + memmove(actual->project[numjoins], fjoin, temp); pos.y = pos.x; actual->projpos[numjoins] = pos; actual++; @@ -701,7 +701,7 @@ void selfjoin(InputIterator actual, InputIterator end) if(actual->address_host_table[pos] < 0) continue; tam = actual->rule_names[x+1] - actual->rule_names[x] - 2; - memcpy(rulecpy, actual->address_host_table + pos + 1, tam * sizeof(int)); + memmove(rulecpy, actual->address_host_table + pos + 1, tam * sizeof(int)); cont = 0; for(y = 0; y < tam; y++) { @@ -735,7 +735,7 @@ void selfjoin(InputIterator actual, InputIterator end) temp = x - 1; tam = cont * sizeof(int); actual->selfjoin[temp] = (int *)malloc(tam); - memcpy(actual->selfjoin[temp], fjoin, tam); + memmove(actual->selfjoin[temp], fjoin, tam); actual->numselfj[temp] = cont; } actual++; @@ -772,7 +772,7 @@ void consulta(int *query, int qsize, int qname, rulenode *res) size = cont1 * sizeof(int); res->select = (int **)malloc(sizeof(int *)); res->select[0] = (int *)malloc(size); - memcpy(res->select[0], sel, size); + memmove(res->select[0], sel, size); cont1 = 0; } if(cont2 > 0) @@ -780,7 +780,7 @@ void consulta(int *query, int qsize, int qname, rulenode *res) size = cont2 * sizeof(int); res->project = (int **)malloc(sizeof(int *)); res->project[0] = (int *)malloc(size); - memcpy(res->project[0], pro, size); + memmove(res->project[0], pro, size); } for(x = 0; x < qsize; x++) { @@ -817,7 +817,7 @@ void consulta(int *query, int qsize, int qname, rulenode *res) size = cont1 * sizeof(int); res->selfjoin = (int **)malloc(sizeof(int *)); res->selfjoin[0] = (int *)malloc(size); - memcpy(res->selfjoin[0], sel, size); + memmove(res->selfjoin[0], sel, size); } } diff --git a/packages/cuda/memory.cu b/packages/cuda/memory.cu index e57ca39b3..168a1e6a3 100644 --- a/packages/cuda/memory.cu +++ b/packages/cuda/memory.cu @@ -346,7 +346,7 @@ int cargarcpu(int name, int num_rows, int num_columns, int is_fact, int *address } for(; x < numcpu; x++) { - memcpy(temp + inc, temp_storage[x].dev_address, temp_storage[x].size); + memmove(temp + inc, temp_storage[x].dev_address, temp_storage[x].size); inc += temp_storage[x].size / sizeof(int); free(temp_storage[x].dev_address); } diff --git a/packages/cuda/old/cuda.c b/packages/cuda/old/cuda.c index 0748e75b7..8aa1f83bc 100755 --- a/packages/cuda/old/cuda.c +++ b/packages/cuda/old/cuda.c @@ -376,12 +376,12 @@ load_rule( void ) { pred->is_fact = FALSE; x = (strlen(strname) + 1) * sizeof(char); pred->predname = (char *)malloc(x); - memcpy(pred->predname, strname, x); + memmove(pred->predname, strname, x); nvec = (int32_t *)malloc(sizeof(int32_t)*(ptr-vec)); - memcpy(nvec, vec, sizeof(int32_t)*(ptr-vec)); + memmove(nvec, vec, sizeof(int32_t)*(ptr-vec)); pred->address_host_table = nvec; pred->negatives = (int32_t *)malloc(sizeof(int32_t) * cont); - memcpy(pred->negatives, neg, sizeof(int32_t) * cont); + memmove(pred->negatives, neg, sizeof(int32_t) * cont); Cuda_NewRule( pred ); return YAP_Unify(YAP_ARG4, YAP_MkIntTerm((YAP_Int)pred)); } diff --git a/packages/cuda/old/dbio.cu b/packages/cuda/old/dbio.cu index 6b0fe78b4..f68b2f711 100644 --- a/packages/cuda/old/dbio.cu +++ b/packages/cuda/old/dbio.cu @@ -180,7 +180,7 @@ void postgresRead(PGconn **ret, vector *L, int *inpquery, char *names, { numt = (strlen(tok) + 1) * sizeof(char); qrs[x] = (char *)malloc(numt); - memcpy(qrs[x], tok, numt); + memmove(qrs[x], tok, numt); } x += 2; } @@ -264,7 +264,7 @@ void postgresRead(PGconn **ret, vector *L, int *inpquery, char *names, L->at(z).address_host_table = mat; numc = (strlen(tok) + 1) * sizeof(char); L->at(z).predname = (char *)malloc(numc); - memcpy(L->at(z).predname, tok, numc); + memmove(L->at(z).predname, tok, numc); PQclear(pgr); tok = strtok(NULL, " "); z++; diff --git a/packages/cuda/old/lista.cu b/packages/cuda/old/lista.cu index f4d7cbb48..d203da469 100755 --- a/packages/cuda/old/lista.cu +++ b/packages/cuda/old/lista.cu @@ -114,7 +114,7 @@ void movebpreds(InputIterator rules, InputIterator end) subs = rules->rule_names[x+1] - rules->rule_names[x]; if(rules->address_host_table[rules->rule_names[x]] > 0) { - memcpy(rest + cont, rules->address_host_table + rules->rule_names[x], subs * sizeof(int)); + memmove(rest + cont, rules->address_host_table + rules->rule_names[x], subs * sizeof(int)); cont += subs; } else @@ -123,17 +123,17 @@ void movebpreds(InputIterator rules, InputIterator end) subs--; if(rules->address_host_table[pos] > 0 && rules->address_host_table[pos+1] > 0) { - memcpy(move2 + cont3, rules->address_host_table + rules->rule_names[x], subs * sizeof(int)); + memmove(move2 + cont3, rules->address_host_table + rules->rule_names[x], subs * sizeof(int)); cont3 += subs; } else { - memcpy(move + cont2, rules->address_host_table + rules->rule_names[x], subs * sizeof(int)); + memmove(move + cont2, rules->address_host_table + rules->rule_names[x], subs * sizeof(int)); cont2 += subs; } } } - memcpy(rules->address_host_table, rest, cont * sizeof(int)); + memmove(rules->address_host_table, rest, cont * sizeof(int)); pos = 1; for(x = 1; x <= total; x++) @@ -178,7 +178,7 @@ void movebpreds(InputIterator rules, InputIterator end) pos += 2; cont = closestpred(rules->rule_names, rules->num_rows, p1); - memcpy(rules->preds[cont] + rules->numpreds[cont].x, move + cont2, total); + memmove(rules->preds[cont] + rules->numpreds[cont].x, move + cont2, total); rules->numpreds[cont].x += 3; cont2 += 3; } @@ -212,19 +212,19 @@ void movebpreds(InputIterator rules, InputIterator end) cont2 = closestpred(rules->rule_names, rules->num_rows, p2); if(cont == cont2) { - memcpy(rules->preds[cont] + rules->numpreds[cont].x, move2 + cont3, total); + memmove(rules->preds[cont] + rules->numpreds[cont].x, move2 + cont3, total); rules->numpreds[cont].x += 3; } else { if(cont > cont2) { - memcpy(rules->preds[cont] + rules->numpreds[cont].x + rules->numpreds[cont].y, move2 + cont3, total); + memmove(rules->preds[cont] + rules->numpreds[cont].x + rules->numpreds[cont].y, move2 + cont3, total); rules->numpreds[cont].y += 3; } else { - memcpy(rules->preds[cont2] + rules->numpreds[cont2].x + rules->numpreds[cont2].y, move2 + cont3, total); + memmove(rules->preds[cont2] + rules->numpreds[cont2].x + rules->numpreds[cont2].y, move2 + cont3, total); rules->numpreds[cont2].y += 3; } } @@ -345,7 +345,7 @@ void seleccion(InputIterator actual, InputIterator end) sl = x - 1; tam = cont * sizeof(int); actual->select[sl] = (int *)malloc(tam); - memcpy(actual->select[sl], pv, tam); + memmove(actual->select[sl], pv, tam); actual->numsel[sl] = cont; } actual++; @@ -480,9 +480,9 @@ int2 columnsproject(int *first, int tam, int *rule, int ini, int fin, int sini, temp = ret.y * sizeof(int); free(*newrule); *newrule = (int *)malloc(temp); - memcpy(*newrule, pv, temp); + memmove(*newrule, pv, temp); *res = (int *)malloc(temp); - memcpy(*res, pv2, temp); + memmove(*res, pv2, temp); return ret; } @@ -509,7 +509,7 @@ int wherejoin(int *tmprule, int tmplen, int *rule, int tam2, int **res) temp = cont * sizeof(int); *res = (int *)malloc(temp); - memcpy(*res, joins, temp); + memmove(*res, joins, temp); return cont; } @@ -611,7 +611,7 @@ void proyeccion(InputIterator actual, InputIterator end) temp = pos.x * sizeof(int); actual->project[0] = (int *)malloc(temp); - memcpy(actual->project[0], fjoin, temp); + memmove(actual->project[0], fjoin, temp); pos.y = pos.x; actual->projpos[0] = pos; actual++; @@ -628,7 +628,7 @@ void proyeccion(InputIterator actual, InputIterator end) pos.y = actual->rule_names[2] - actual->rule_names[1] - 2; temp = pos.y * sizeof(int); pv = (int *)malloc(temp); - memcpy(pv, actual->address_host_table + actual->rule_names[1] + 1, temp); + memmove(pv, actual->address_host_table + actual->rule_names[1] + 1, temp); for(x = 2, y = 0; x <= numjoins; x++, y++) { @@ -676,7 +676,7 @@ void proyeccion(InputIterator actual, InputIterator end) } temp = pos.x * sizeof(int); actual->project[numjoins] = (int *)malloc(temp); - memcpy(actual->project[numjoins], fjoin, temp); + memmove(actual->project[numjoins], fjoin, temp); pos.y = pos.x; actual->projpos[numjoins] = pos; actual++; @@ -701,7 +701,7 @@ void selfjoin(InputIterator actual, InputIterator end) if(actual->address_host_table[pos] < 0) continue; tam = actual->rule_names[x+1] - actual->rule_names[x] - 2; - memcpy(rulecpy, actual->address_host_table + pos + 1, tam * sizeof(int)); + memmove(rulecpy, actual->address_host_table + pos + 1, tam * sizeof(int)); cont = 0; for(y = 0; y < tam; y++) { @@ -735,7 +735,7 @@ void selfjoin(InputIterator actual, InputIterator end) temp = x - 1; tam = cont * sizeof(int); actual->selfjoin[temp] = (int *)malloc(tam); - memcpy(actual->selfjoin[temp], fjoin, tam); + memmove(actual->selfjoin[temp], fjoin, tam); actual->numselfj[temp] = cont; } actual++; @@ -772,7 +772,7 @@ void consulta(int *query, int qsize, int qname, rulenode *res) size = cont1 * sizeof(int); res->select = (int **)malloc(sizeof(int *)); res->select[0] = (int *)malloc(size); - memcpy(res->select[0], sel, size); + memmove(res->select[0], sel, size); cont1 = 0; } if(cont2 > 0) @@ -780,7 +780,7 @@ void consulta(int *query, int qsize, int qname, rulenode *res) size = cont2 * sizeof(int); res->project = (int **)malloc(sizeof(int *)); res->project[0] = (int *)malloc(size); - memcpy(res->project[0], pro, size); + memmove(res->project[0], pro, size); } for(x = 0; x < qsize; x++) { @@ -817,7 +817,7 @@ void consulta(int *query, int qsize, int qname, rulenode *res) size = cont1 * sizeof(int); res->selfjoin = (int **)malloc(sizeof(int *)); res->selfjoin[0] = (int *)malloc(size); - memcpy(res->selfjoin[0], sel, size); + memmove(res->selfjoin[0], sel, size); } } diff --git a/packages/cuda/old/memory.cu b/packages/cuda/old/memory.cu index 70036e07b..7e0404f79 100755 --- a/packages/cuda/old/memory.cu +++ b/packages/cuda/old/memory.cu @@ -346,7 +346,7 @@ int cargarcpu(int name, int num_rows, int num_columns, int is_fact, int *address } for(; x < numcpu; x++) { - memcpy(temp + inc, temp_storage[x].dev_address, temp_storage[x].size); + memmove(temp + inc, temp_storage[x].dev_address, temp_storage[x].size); inc += temp_storage[x].size / sizeof(int); free(temp_storage[x].dev_address); } diff --git a/packages/cuda/selectproyectcpu.cpp b/packages/cuda/selectproyectcpu.cpp index 5ae091e13..876674766 100644 --- a/packages/cuda/selectproyectcpu.cpp +++ b/packages/cuda/selectproyectcpu.cpp @@ -117,7 +117,7 @@ int selectproyectcpu(int *dop1, int rows, int cols, int head_size, int *select, ptr = fres; for(x = 0; x < NUM_T; x++) { - memcpy(ptr, vec[x].data(), ini[x] * sizeof(int)); + memmove(ptr, vec[x].data(), ini[x] * sizeof(int)); ptr += ini[x]; } *ret = fres; @@ -237,7 +237,7 @@ int selectproyectcpu2(int *dop1, int rows, int cols, int *select, int numselect, ptr = lres; for(x = 0; x < NUM_T; x++) { - memcpy(ptr, lis[x], cont[x] * sizeof(int)); + memmove(ptr, lis[x], cont[x] * sizeof(int)); ptr += cont[x]; } if(list != NULL) @@ -246,7 +246,7 @@ int selectproyectcpu2(int *dop1, int rows, int cols, int *select, int numselect, ptr = fres; for(x = 0; x < NUM_T; x++) { - memcpy(ptr, vec[x], cont[x] * sizeof(int)); + memmove(ptr, vec[x], cont[x] * sizeof(int)); ptr += cont[x]; } *ret = fres; @@ -373,7 +373,7 @@ int selectproyectcpu3(int *dop1, int rows, int cols, int *select, int numselect, ptr = lres; for(x = 0; x < NUM_T; x++) { - memcpy(ptr, lis[x].data(), ini[x] * sizeof(int)); + memmove(ptr, lis[x].data(), ini[x] * sizeof(int)); ptr += ini[x]; } if(list != NULL) @@ -382,7 +382,7 @@ int selectproyectcpu3(int *dop1, int rows, int cols, int *select, int numselect, ptr = fres; for(x = 0; x < NUM_T; x++) { - memcpy(ptr, vec[x].data(), ini[x] * sizeof(int)); + memmove(ptr, vec[x].data(), ini[x] * sizeof(int)); ptr += ini[x]; } *ret = fres; diff --git a/packages/cuda/unioncpu2.cpp b/packages/cuda/unioncpu2.cpp index 6f1e3cd81..92091be86 100644 --- a/packages/cuda/unioncpu2.cpp +++ b/packages/cuda/unioncpu2.cpp @@ -25,7 +25,7 @@ int unircpu(int *res, int rows, int tipo, int **ret) { size = nrows * tipo * sizeof(int); nres = (int *)malloc(size); - memcpy(nres, res, size); + memmove(nres, res, size); free(*ret); *ret = nres; }*/ @@ -41,7 +41,7 @@ int unircpu(int *res, int rows, int tipo, int **ret) { size = nrows * tipo * sizeof(int); nres = (int *)malloc(size); - memcpy(nres, res, size); + memmove(nres, res, size); free(*ret); *ret = nres; }*/ @@ -57,7 +57,7 @@ int unircpu(int *res, int rows, int tipo, int **ret) { size = nrows * tipo * sizeof(int); nres = (int *)malloc(size); - memcpy(nres, res, size); + memmove(nres, res, size); free(*ret); *ret = nres; }*/ diff --git a/packages/myddas/pl/myddas.ypp b/packages/myddas/pl/myddas.ypp index 356c0ba6c..0cd260b4d 100644 --- a/packages/myddas/pl/myddas.ypp +++ b/packages/myddas/pl/myddas.ypp @@ -168,6 +168,7 @@ :- use_module(myddas_errors,[ '$error_checks'/1 + ]). :- use_module(myddas_prolog2sql,[ @@ -180,6 +181,7 @@ member/2 ]). +:- set(verbose,silent). diff --git a/packages/myddas/pl/myddas_assert_predicates.ypp b/packages/myddas/pl/myddas_assert_predicates.ypp index 33c4fc976..ac34345f7 100644 --- a/packages/myddas/pl/myddas_assert_predicates.ypp +++ b/packages/myddas/pl/myddas_assert_predicates.ypp @@ -101,7 +101,7 @@ db_import(Connection,RelationName,PredName0) :- not c_db_check_if_exists_pred(PredName,Arity,Module), R=..[relation,PredName,Arity,RelationName], % assert relation fact - assert(user:R), + assert(Module:R), Size is 2*Arity, length(TypesList, Size), @@ -114,15 +114,15 @@ db_import(Connection,RelationName,PredName0) :- % build PredName functor functor(P,PredName,Arity), P=..[PredName|LA], - - M=myddas_assert_predicates, %build PredName clause - table_access_predicate( ConType, Con, Arity, P, LA, M, Assert ), - assert(Module:Assert), + table_access_predicate( ConType, Con, Arity, P, LA, Modulelisting, Assert ), + assert_static(Module:Assert), c_db_add_preds(PredName,Arity,Module,Con). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +:- meta_predicate db_view(:,0). +:- meta_predicate db_view(+,:,0). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % db_view/3 @@ -289,46 +289,47 @@ table_attributes( sqlite3, Con, RelationName, TypesList ) :- % predicate for DB-> query + table_access_predicate( mysql, Con, Arity, P, LA, M, - ( P :- M:('$copy_term_nv'(P,[],G,_), - translate(G,G,Code), + ( P :- user:(myddas_util_predicates:'$copy_term_nv'(P,[],G,_), + myddas_prolog2sql:translate(G,G,Code), queries_atom(Code,FinalSQL), db_my_result_set(Mode), - '$write_or_not'(FinalSQL), + myddas_util_predicates:'$write_or_not'(FinalSQL), c_db_my_query(FinalSQL,ResultSet,Con,Mode,_), !, c_db_my_row(ResultSet,Arity,LA) ))). -table_access_predicate( postgres, Con, Arity, P, LA, M, - ( P :- M:('$copy_term_nv'(P,[],G,_), - translate(G,G,Code), - queries_atom(Code,FinalSQL), - db_my_result_set(Mode), - '$write_or_not'(FinalSQL), +table_access_predicate( postgres, Con, Arity, P, LA, _M, + ( P :- myddas_util_predicates:'$copy_term_nv'(P,[],G,_), + myddas_prolog2sql:translate(M:G,M:G,Code), + myddas_prolog2sql:queries_atom(Code,FinalSQL), + myddas_postgres:postgres_result_set(Mode), + myddas_util_predicates:'$write_or_not'(FinalSQL), c_postgres_query(FinalSQL,ResultSet,Con,Mode,_), !, c_postgsres_row(ResultSet,Arity,LA) ))). table_access_predicate( sqlite3, Con, Arity, P, LA, M, - ( P :- M:('$copy_term_nv'(P,[],G,_), - translate(G,G,Code), - queries_atom(Code,FinalSQL), - sqlite3_result_set(Mode), - '$write_or_not'(FinalSQL), - c_sqlite3_query(FinalSQL,ResultSet,Con,Mode,_), + ( P :- (myddas_util_predicates:'$copy_term_nv'(P,[],G,_), + myddas_prolog2sql:translate(G,G,Code), + myddas_prolog2sql:queries_atom(Code,FinalSQL), + myddas_sqlite3:sqlite3_result_set(Mode), + myddas_util_predicates:'$write_or_not'(FinalSQL), + user:c_sqlite3_query(FinalSQL,ResultSet,Con,Mode,_), !, - sqlite3_row(ResultSet,Arity,LA) + myddas_aqlite3:sqlite3_row(ResultSet,Arity,LA) ) )). table_access_predicate( odbc, Con, Arity, P, LA, M, - ( P :- M:('$copy_term_nv'(P,[],G,_), - translate(G,G,Code), - queries_atom(Code,FinalSQL), - c_odbc_result_set(Mode), - '$write_or_not'(FinalSQL), - c_odbc_query(FinalSQL,ResultSet,Con,Mode,_), + ( P :- M:(myddas_util_predicates:'$copy_term_nv'(P,[],G,_), + myddas_prolog2sql:translate(G,G,Code), + myddas_prolog2sql:queries_atom(Code,FinalSQL), + myddas_odbc:odbc_result_set(Mode), + 'myddas_util_predicates:$write_or_not'(FinalSQL), + myddas_odbc:c_odbc_query(FinalSQL,ResultSet,Con,Mode,_), !, - c_odbc_row(ResultSet,Arity,LA) + myddas_odbc:c_odbc_row(ResultSet,Arity,LA) ) )). table_insert( mysql, Con, RelationName, TypesList, Predicate, LA, diff --git a/packages/myddas/pl/myddas_driver.ypp b/packages/myddas/pl/myddas_driver.ypp index 0a08d34b4..07db8631f 100644 --- a/packages/myddas/pl/myddas_driver.ypp +++ b/packages/myddas/pl/myddas_driver.ypp @@ -56,6 +56,11 @@ DBMS(row)/3 ]). + +:- use_module(library(lists)). + :- use_module(library(maplist)). + + :- use_module(myddas,[ db_sql/3 ]). diff --git a/packages/myddas/sqlite3/CMakeLists.txt b/packages/myddas/sqlite3/CMakeLists.txt index 863278b17..ca8daca1a 100644 --- a/packages/myddas/sqlite3/CMakeLists.txt +++ b/packages/myddas/sqlite3/CMakeLists.txt @@ -29,7 +29,6 @@ add_definitions(-DSQLITE_ENABLE_JSON1=1 ) add_definitions(-DSQLITE_ENABLE_RBU=1 ) add_definitions(-DSQLITE_ENABLE_RTREE=1 ) - add_definitions(-DSQLITE_ENABLE_FTS5=1 ) SET_PROPERTY(DIRECTORY PROPERTY COMPILE_DEFINITIONS YAP_KERNEL=1 ) @@ -47,6 +46,8 @@ else() add_library( YAPsqlite3 SHARED ${YAPSQLITE3_SOURCES}) + target_link_libraries(YAPsqlite3 libYap ) + set_target_properties(YAPsqlite3 PROPERTIES # RPATH ${libdir} VERSION ${LIBYAPTAI_FULL_VERSION} diff --git a/packages/myddas/sqlite3/myddas_sqlite3.c b/packages/myddas/sqlite3/myddas_sqlite3.c index 7df12c11d..77f214ab5 100644 --- a/packages/myddas/sqlite3/myddas_sqlite3.c +++ b/packages/myddas/sqlite3/myddas_sqlite3.c @@ -595,7 +595,7 @@ static Int c_sqlite3_row(USES_REGS1) { size_t bytes = sqlite3_column_bytes(res_set->stmt, i); void *pt; tf = Yap_AllocExternalDataInStack(EXTERNAL_BLOB, bytes, &pt); - memcpy(pt, sqlite3_column_blob(res_set->stmt, i), bytes); + memmove(pt, sqlite3_column_blob(res_set->stmt, i), bytes); } break; case SQLITE_NULL: null_atom[0] = MkIntegerTerm(null_id++); diff --git a/packages/myddas/sqlite3/sqlitest.yap b/packages/myddas/sqlite3/sqlitest.yap index 532d888ef..a800ffadf 100644 --- a/packages/myddas/sqlite3/sqlitest.yap +++ b/packages/myddas/sqlite3/sqlitest.yap @@ -1,4 +1,7 @@ :- stop_low_level_trace. + + +:- use_module(library(lists)). :- use_module(library(maplist)). :- use_module(library(myddas)). @@ -7,13 +10,13 @@ main :- main_, close. main_ :- - go, + catch(go,E,writeln(E)), fail. main_ . init :- - % db_open(sqlite3, '/data/user/0/pt.up.yap.yapdroid/files/Yap/chinook.db', _, _), - db_open(sqlite3, 'chinook.db', _, _), + db_open(sqlite3, '/data/user/0/pt.up.yap.yapdroid/files/Yap/chinook.db', _, _), + % db_open(sqlite3, 'chinook.db', _, _), writeln('chinook has landed'). go :- @@ -25,6 +28,11 @@ go :- db_import('tracks', tracks), writeln(('tracks -> tracks')). + +go :- +% X=1, + artists(X,Y), + writeln(X:Y). go :- writeln(db_get_attributes_types), db_get_attributes_types(albums,Als), @@ -54,6 +62,7 @@ go :- db_describe(T,tableinfo(FieldID,Type,Null,Primary,Default,'')), writeln(T:tableinfo(FieldID,Type,Null,Primary,Default,'')). + go :- writeln(access), go_cut0. @@ -70,11 +79,6 @@ go :- go :- go_cut1. -go :- - X=1, - artists(X,Y), - writeln(X:Y). - go_cut0 :- artists(X,Y), writeln(X:Y), @@ -82,7 +86,7 @@ go_cut0 :- go_cut1 :- - X=1, +% X=1, artists(X,Y), writeln(X:Y), !. @@ -90,4 +94,6 @@ go_cut1 :- close :- db_close. -:- main. + + +:- initialization(main). diff --git a/packages/myddas/sqlite3/src/sqlite3.c b/packages/myddas/sqlite3/src/sqlite3.c index 73c69efbd..8d1cc3579 100644 --- a/packages/myddas/sqlite3/src/sqlite3.c +++ b/packages/myddas/sqlite3/src/sqlite3.c @@ -12707,14 +12707,14 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*); #include /* -** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY. -** This allows better measurements of where memcpy() is used when running -** cachegrind. But this macro version of memcpy() is very slow so it +** Use a macro to replace memmove() if compiled with SQLITE_INLINE_MEMCPY. +** This allows better measurements of where memmove() is used when running +** cachegrind. But this macro version of memmove() is very slow so it ** should not be used in production. This is a performance measurement ** hack only. */ #ifdef SQLITE_INLINE_MEMCPY -# define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\ +# define memmove(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\ int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);} #endif @@ -20771,7 +20771,7 @@ static void currentTimeFunc( #else sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); pTm = gmtime(&t); - if( pTm ) memcpy(&sNow, pTm, sizeof(sNow)); + if( pTm ) memmove(&sNow, pTm, sizeof(sNow)); sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); #endif if( pTm ){ @@ -21948,7 +21948,7 @@ static void *sqlite3MemMalloc(int nByte){ if( mem.nBacktrace ){ void *aAddr[40]; pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1; - memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*)); + memmove(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*)); assert(pBt[0]); if( mem.xBacktrace ){ mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]); @@ -21957,7 +21957,7 @@ static void *sqlite3MemMalloc(int nByte){ pHdr->nBacktrace = 0; } if( mem.nTitle ){ - memcpy(z, mem.zTitle, mem.nTitle); + memmove(z, mem.zTitle, mem.nTitle); } pHdr->iSize = nByte; adjustStats(nByte, +1); @@ -22024,7 +22024,7 @@ static void *sqlite3MemRealloc(void *pPrior, int nByte){ pOldHdr = sqlite3MemsysGetHeader(pPrior); pNew = sqlite3MemMalloc(nByte); if( pNew ){ - memcpy(pNew, pPrior, (int)(nByteiSize ? nByte : pOldHdr->iSize)); + memmove(pNew, pPrior, (int)(nByteiSize ? nByte : pOldHdr->iSize)); if( nByte>pOldHdr->iSize ){ randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize); } @@ -22130,7 +22130,7 @@ SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){ unsigned int n = sqlite3Strlen30(zTitle) + 1; sqlite3_mutex_enter(mem.mutex); if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1; - memcpy(mem.zTitle, zTitle, n); + memmove(mem.zTitle, zTitle, n); mem.zTitle[n] = 0; mem.nTitle = ROUND8(n); sqlite3_mutex_leave(mem.mutex); @@ -22743,9 +22743,9 @@ static void *memsys3Realloc(void *pPrior, int nBytes){ p = memsys3MallocUnsafe(nBytes); if( p ){ if( nOldlookaside.sz); + memmove(pNew, p, db->lookaside.sz); sqlite3DbFree(db, p); } }else{ @@ -25748,7 +25748,7 @@ SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){ n = strlen(z) + 1; zNew = sqlite3DbMallocRaw(db, n); if( zNew ){ - memcpy(zNew, z, n); + memmove(zNew, z, n); } return zNew; } @@ -25761,7 +25761,7 @@ SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){ assert( (n&0x7fffffff)==n ); zNew = sqlite3DbMallocRawNN(db, n+1); if( zNew ){ - memcpy(zNew, z, (size_t)n); + memmove(zNew, z, (size_t)n); zNew[n] = 0; } return zNew; @@ -26352,7 +26352,7 @@ SQLITE_PRIVATE void sqlite3VXPrintf( if( exp>350 ){ bufpt = buf; buf[0] = prefix; - memcpy(buf+(prefix!=0),"Inf",4); + memmove(buf+(prefix!=0),"Inf",4); length = 3+(prefix!=0); break; } @@ -26660,7 +26660,7 @@ static int sqlite3StrAccumEnlarge(StrAccum *p, int N){ } if( zNew ){ assert( p->zText!=0 || p->nChar==0 ); - if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar); + if( !isMalloced(p) && p->nChar>0 ) memmove(zNew, p->zText, p->nChar); p->zText = zNew; p->nAlloc = sqlite3DbMallocSize(p->db, zNew); p->printfFlags |= SQLITE_PRINTF_MALLOCED; @@ -26695,7 +26695,7 @@ SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){ static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){ N = sqlite3StrAccumEnlarge(p, N); if( N>0 ){ - memcpy(&p->zText[p->nChar], z, N); + memmove(&p->zText[p->nChar], z, N); p->nChar += N; } } @@ -26714,7 +26714,7 @@ SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){ }else if( N ){ assert( p->zText ); p->nChar += N; - memcpy(&p->zText[p->nChar-N], z, N); + memmove(&p->zText[p->nChar-N], z, N); } } @@ -26736,7 +26736,7 @@ static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){ assert( p->mxAlloc>0 && !isMalloced(p) ); zText = sqlite3DbMallocRaw(p->db, p->nChar+1 ); if( zText ){ - memcpy(zText, p->zText, p->nChar+1); + memmove(zText, p->zText, p->nChar+1); p->printfFlags |= SQLITE_PRINTF_MALLOCED; }else{ setStrAccumError(p, STRACCUM_NOMEM); @@ -27637,14 +27637,14 @@ SQLITE_API void sqlite3_randomness(int N, void *pBuf){ */ static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng; SQLITE_PRIVATE void sqlite3PrngSaveState(void){ - memcpy( + memmove( &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), &GLOBAL(struct sqlite3PrngType, sqlite3Prng), sizeof(sqlite3Prng) ); } SQLITE_PRIVATE void sqlite3PrngRestoreState(void){ - memcpy( + memmove( &GLOBAL(struct sqlite3PrngType, sqlite3Prng), &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), sizeof(sqlite3Prng) @@ -29174,7 +29174,7 @@ SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){ for(k=i; sqlite3Isxdigit(z[k]); k++){ u = u*16 + sqlite3HexToInt(z[k]); } - memcpy(pOut, &u, 8); + memmove(pOut, &u, 8); return (z[k]==0 && k-i<=16) ? 0 : 2; }else #endif /* SQLITE_OMIT_HEX_INTEGER */ @@ -29215,7 +29215,7 @@ SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){ u = u*16 + sqlite3HexToInt(zNum[i]); } if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){ - memcpy(pValue, &u, 4); + memmove(pValue, &u, 4); return 1; }else{ return 0; @@ -29648,15 +29648,15 @@ SQLITE_PRIVATE int sqlite3VarintLen(u64 v){ SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){ #if SQLITE_BYTEORDER==4321 u32 x; - memcpy(&x,p,4); + memmove(&x,p,4); return x; #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 u32 x; - memcpy(&x,p,4); + memmove(&x,p,4); return __builtin_bswap32(x); #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 u32 x; - memcpy(&x,p,4); + memmove(&x,p,4); return _byteswap_ulong(x); #else testcase( p[0]&0x80 ); @@ -29665,13 +29665,13 @@ SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){ } SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){ #if SQLITE_BYTEORDER==4321 - memcpy(p,&v,4); + memmove(p,&v,4); #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 u32 x = __builtin_bswap32(v); - memcpy(p,&x,4); + memmove(p,&x,4); #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 u32 x = _byteswap_ulong(v); - memcpy(p,&x,4); + memmove(p,&x,4); #else p[0] = (u8)(v>>24); p[1] = (u8)(v>>16); @@ -29945,7 +29945,7 @@ SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){ assert( sizeof(x)==8 && sizeof(a)==8 ); if( x<=1 ) return 0; if( x<=2000000000 ) return sqlite3LogEst((u64)x); - memcpy(&a, &x, 8); + memmove(&a, &x, 8); e = (a>>52) - 1022; return e*10; } @@ -30042,7 +30042,7 @@ SQLITE_PRIVATE VList *sqlite3VListAdd( z = (char*)&pIn[i+2]; pIn[1] = i+nInt; assert( pIn[1]<=pIn[0] ); - memcpy(z, zName, nName); + memmove(z, zName, nName); z[nName] = 0; return pIn; } @@ -31676,7 +31676,7 @@ static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){ pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) ); if( pNew==0 ) return 0; pNew->zCanonicalName = (char*)&pNew[1]; - memcpy(pNew->zCanonicalName, zAbsoluteName, n+1); + memmove(pNew->zCanonicalName, zAbsoluteName, n+1); n = vxworksSimplifyName(pNew->zCanonicalName, n); /* Search for an existing entry that matching the canonical name. @@ -32093,7 +32093,7 @@ static int findInodeInfo( return SQLITE_NOMEM_BKPT; } memset(pInode, 0, sizeof(*pInode)); - memcpy(&pInode->fileId, &fileId, sizeof(fileId)); + memmove(&pInode->fileId, &fileId, sizeof(fileId)); pInode->nRef = 1; pInode->pNext = inodeList; pInode->pPrev = 0; @@ -33961,14 +33961,14 @@ static int unixRead( #if SQLITE_MAX_MMAP_SIZE>0 /* Deal with as much of this read request as possible by transfering - ** data from the memory mapping using memcpy(). */ + ** data from the memory mapping using memmove(). */ if( offsetmmapSize ){ if( offset+amt <= pFile->mmapSize ){ - memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); + memmove(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); return SQLITE_OK; }else{ int nCopy = pFile->mmapSize - offset; - memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); + memmove(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); pBuf = &((u8 *)pBuf)[nCopy]; amt -= nCopy; offset += nCopy; @@ -34096,14 +34096,14 @@ static int unixWrite( #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0 /* Deal with as much of this write request as possible by transfering - ** data from the memory mapping using memcpy(). */ + ** data from the memory mapping using memmove(). */ if( offsetmmapSize ){ if( offset+amt <= pFile->mmapSize ){ - memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); + memmove(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); return SQLITE_OK; }else{ int nCopy = pFile->mmapSize - offset; - memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); + memmove(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); pBuf = &((u8 *)pBuf)[nCopy]; amt -= nCopy; offset += nCopy; @@ -36471,7 +36471,7 @@ static int findCreateFileMode( if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK; nDb--; } - memcpy(zDb, zPath, nDb); + memmove(zDb, zPath, nDb); zDb[nDb] = '\0'; rc = getFileMode(zDb, pMode, pUid, pGid); @@ -36944,7 +36944,7 @@ static int unixFullPathname( rc = SQLITE_CANTOPEN_BKPT; }else{ memmove(&zDel[n], zDel, nByte+1); - memcpy(zDel, zIn, n); + memmove(zDel, zIn, n); nByte += n; } } @@ -37059,8 +37059,8 @@ static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ if( fd<0 ){ time_t t; time(&t); - memcpy(zBuf, &t, sizeof(t)); - memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid)); + memmove(zBuf, &t, sizeof(t)); + memmove(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid)); assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf ); nBuf = sizeof(t) + sizeof(randomnessPid); }else{ @@ -37782,7 +37782,7 @@ static int proxyTakeConch(unixFile *pFile){ if( pathLen>=MAXPATHLEN ){ pathLen=MAXPATHLEN-1; } - memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen); + memmove(lockPath, &readBuf[PROXY_PATHINDEX], pathLen); lockPath[pathLen] = 0; tempLockPath = lockPath; tryOldLockPath = 1; @@ -37832,7 +37832,7 @@ static int proxyTakeConch(unixFile *pFile){ int writeSize = 0; writeBuffer[0] = (char)PROXY_CONCHVERSION; - memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN); + memmove(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN); if( pCtx->lockProxyPath!=NULL ){ strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN); @@ -37979,7 +37979,7 @@ static int proxyCreateConchPathname(char *dbPath, char **pConchPath){ if( conchPath==0 ){ return SQLITE_NOMEM_BKPT; } - memcpy(conchPath, dbPath, len+1); + memmove(conchPath, dbPath, len+1); /* now insert a "." before the last / character */ for( i=(len-1); i>=0; i-- ){ @@ -37995,7 +37995,7 @@ static int proxyCreateConchPathname(char *dbPath, char **pConchPath){ } /* append the "-conch" suffix to the file */ - memcpy(&conchPath[i+1], "-conch", 7); + memmove(&conchPath[i+1], "-conch", 7); assert( (int)strlen(conchPath) == len+7 ); return SQLITE_OK; @@ -38055,7 +38055,7 @@ static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){ /* dot lock style uses the locking context to store the dot lock ** file path */ int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX); - memcpy(dbPath, (char *)pFile->lockingContext, len + 1); + memmove(dbPath, (char *)pFile->lockingContext, len + 1); }else{ /* all other styles use the locking context to store the db file path */ assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); @@ -40047,7 +40047,7 @@ SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){ #if defined(SQLITE_WIN32_HAS_ANSI) if( nMin>0 ){ memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); - memcpy(zDbgBuf, zBuf, nMin); + memmove(zDbgBuf, zBuf, nMin); osOutputDebugStringA(zDbgBuf); }else{ osOutputDebugStringA(zBuf); @@ -40063,7 +40063,7 @@ SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){ #else if( nMin>0 ){ memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); - memcpy(zDbgBuf, zBuf, nMin); + memmove(zDbgBuf, zBuf, nMin); fprintf(stderr, "%s", zDbgBuf); }else{ fprintf(stderr, "%s", zBuf); @@ -41400,16 +41400,16 @@ static int winRead( #if SQLITE_MAX_MMAP_SIZE>0 /* Deal with as much of this read request as possible by transfering - ** data from the memory mapping using memcpy(). */ + ** data from the memory mapping using memmove(). */ if( offsetmmapSize ){ if( offset+amt <= pFile->mmapSize ){ - memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); + memmove(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; }else{ int nCopy = (int)(pFile->mmapSize - offset); - memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); + memmove(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); pBuf = &((u8 *)pBuf)[nCopy]; amt -= nCopy; offset += nCopy; @@ -41478,16 +41478,16 @@ static int winWrite( #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0 /* Deal with as much of this write request as possible by transfering - ** data from the memory mapping using memcpy(). */ + ** data from the memory mapping using memmove(). */ if( offsetmmapSize ){ if( offset+amt <= pFile->mmapSize ){ - memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); + memmove(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; }else{ int nCopy = (int)(pFile->mmapSize - offset); - memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); + memmove(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); pBuf = &((u8 *)pBuf)[nCopy]; amt -= nCopy; offset += nCopy; @@ -44978,7 +44978,7 @@ bitvec_set_rehash: if( aiValues==0 ){ return SQLITE_NOMEM_BKPT; }else{ - memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); + memmove(aiValues, p->u.aHash, sizeof(p->u.aHash)); memset(p->u.apSub, 0, sizeof(p->u.apSub)); p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR; rc = sqlite3BitvecSet(p, i); @@ -45018,7 +45018,7 @@ SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){ }else{ unsigned int j; u32 *aiValues = pBuf; - memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); + memmove(aiValues, p->u.aHash, sizeof(p->u.aHash)); memset(p->u.aHash, 0, sizeof(p->u.aHash)); p->nSet = 0; for(j=0; jnoSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY) || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) ){ - memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); + memmove(zHeader, aJournalMagic, sizeof(aJournalMagic)); put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff); }else{ memset(zHeader, 0, sizeof(aJournalMagic)+4); @@ -50445,7 +50445,7 @@ static int pager_playback_one_page( */ void *pData; pData = pPg->pData; - memcpy(pData, (u8*)aData, pPager->pageSize); + memmove(pData, (u8*)aData, pPager->pageSize); pPager->xReiniter(pPg); /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But ** that call was dangerous and had no detectable benefit since the cache @@ -50456,7 +50456,7 @@ static int pager_playback_one_page( /* If this was page 1, then restore the value of Pager.dbFileVers. ** Do this before any decoding. */ if( pgno==1 ){ - memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers)); + memmove(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers)); } /* Decode the page just read from disk */ @@ -51020,7 +51020,7 @@ static int readDbPage(PgHdr *pPg){ memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers)); }else{ u8 *dbFileVers = &((u8*)pPg->pData)[24]; - memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers)); + memmove(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers)); } } CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT); @@ -52236,7 +52236,7 @@ static int syncJournal(Pager *pPager, int newHdr){ u8 aMagic[8]; u8 zHeader[sizeof(aJournalMagic)+4]; - memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); + memmove(zHeader, aJournalMagic, sizeof(aJournalMagic)); put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec); iNextHdrOffset = journalHdrOffset(pPager); @@ -52394,7 +52394,7 @@ static int pager_write_pagelist(Pager *pPager, PgHdr *pList){ ** page caused the database file to grow, update dbFileSize. */ if( pgno==1 ){ - memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers)); + memmove(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers)); } if( pgno>pPager->dbFileSize ){ pPager->dbFileSize = pgno; @@ -52765,15 +52765,15 @@ SQLITE_PRIVATE int sqlite3PagerOpen( if( zPathname ){ assert( nPathname>0 ); pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri); - memcpy(pPager->zFilename, zPathname, nPathname); - if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri); - memcpy(pPager->zJournal, zPathname, nPathname); - memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2); + memmove(pPager->zFilename, zPathname, nPathname); + if( nUri ) memmove(&pPager->zFilename[nPathname+1], zUri, nUri); + memmove(pPager->zJournal, zPathname, nPathname); + memmove(&pPager->zJournal[nPathname], "-journal\000", 8+2); sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal); #ifndef SQLITE_OMIT_WAL pPager->zWal = &pPager->zJournal[nPathname+8+1]; - memcpy(pPager->zWal, zPathname, nPathname); - memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1); + memmove(pPager->zWal, zPathname, nPathname); + memmove(&pPager->zWal[nPathname], "-wal\000", 4+1); sqlite3FileSuffix3(pPager->zFilename, pPager->zWal); #endif sqlite3DbFree(0, zPathname); @@ -54216,7 +54216,7 @@ static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ ** next time a read transaction is opened the cache will be ** flushed (as the change-counter values will not match). */ const void *pCopy = (const void *)&((const char *)zBuf)[24]; - memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers)); + memmove(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers)); pPager->changeCountDone = 1; } }else{ @@ -56292,9 +56292,9 @@ static void walIndexWriteHdr(Wal *pWal){ pWal->hdr.isInit = 1; pWal->hdr.iVersion = WALINDEX_MAX_VERSION; walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum); - memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr)); + memmove((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr)); walShmBarrier(pWal); - memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr)); + memmove((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr)); } /* @@ -56323,7 +56323,7 @@ static void walEncodeFrame( sqlite3Put4byte(&aFrame[0], iPage); sqlite3Put4byte(&aFrame[4], nTruncate); if( pWal->iReCksum==0 ){ - memcpy(&aFrame[8], pWal->hdr.aSalt, 8); + memmove(&aFrame[8], pWal->hdr.aSalt, 8); nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN); walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); @@ -56777,7 +56777,7 @@ static int walIndexRecover(Wal *pWal){ pWal->hdr.bigEndCksum = (u8)(magic&0x00000001); pWal->szPage = szPage; pWal->nCkpt = sqlite3Get4byte(&aBuf[12]); - memcpy(&pWal->hdr.aSalt, &aBuf[16], 8); + memmove(&pWal->hdr.aSalt, &aBuf[16], 8); /* Verify that the WAL header checksum is correct */ walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, @@ -57084,7 +57084,7 @@ static void walMerge( *paRight = aLeft; *pnRight = iOut; - memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut); + memmove(aLeft, aTmp, sizeof(aTmp[0])*iOut); } /* @@ -57311,7 +57311,7 @@ static void walRestartHdr(Wal *pWal, u32 salt1){ pWal->nCkpt++; pWal->hdr.mxFrame = 0; sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0])); - memcpy(&pWal->hdr.aSalt[1], &salt1, 4); + memmove(&pWal->hdr.aSalt[1], &salt1, 4); walIndexWriteHdr(pWal); pInfo->nBackfill = 0; pInfo->nBackfillAttempted = 0; @@ -57652,9 +57652,9 @@ static int walIndexTryHdr(Wal *pWal, int *pChanged){ ** reordering the reads and writes. */ aHdr = walIndexHdr(pWal); - memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); + memmove(&h1, (void *)&aHdr[0], sizeof(h1)); walShmBarrier(pWal); - memcpy(&h2, (void *)&aHdr[1], sizeof(h2)); + memmove(&h2, (void *)&aHdr[1], sizeof(h2)); if( memcmp(&h1, &h2, sizeof(h1))!=0 ){ return 1; /* Dirty read */ @@ -57669,7 +57669,7 @@ static int walIndexTryHdr(Wal *pWal, int *pChanged){ if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){ *pChanged = 1; - memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr)); + memmove(&pWal->hdr, &h1, sizeof(WalIndexHdr)); pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); testcase( pWal->szPage<=32768 ); testcase( pWal->szPage>=65536 ); @@ -57875,7 +57875,7 @@ static int walBeginShmUnreliable(Wal *pWal, int *pChanged){ ** Assume the in-memory WAL-index substitute is correct and load it ** into pWal->hdr. */ - memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr)); + memmove(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr)); /* Make sure some writer hasn't come in and changed the WAL file out ** from under us, then disconnected, while we were not looking. @@ -58379,7 +58379,7 @@ SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ && pSnapshot->mxFrame>=pInfo->nBackfillAttempted ){ assert( pWal->readLock>0 ); - memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr)); + memmove(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr)); *pChanged = bChanged; }else{ rc = SQLITE_BUSY_SNAPSHOT; @@ -58631,7 +58631,7 @@ SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *p /* Restore the clients cache of the wal-index header to the state it ** was in before the client began writing to the database. */ - memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr)); + memmove(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr)); for(iFrame=pWal->hdr.mxFrame+1; ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; @@ -58939,7 +58939,7 @@ SQLITE_PRIVATE int sqlite3WalFrames( sqlite3Put4byte(&aWalHdr[8], szPage); sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt); if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt); - memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8); + memmove(&aWalHdr[16], pWal->hdr.aSalt, 8); walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum); sqlite3Put4byte(&aWalHdr[24], aCksum[0]); sqlite3Put4byte(&aWalHdr[28], aCksum[1]); @@ -59329,7 +59329,7 @@ SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapsho if( pRet==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ - memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr)); + memmove(pRet, &pWal->hdr, sizeof(WalIndexHdr)); *ppSnapshot = (sqlite3_snapshot*)pRet; } @@ -61882,10 +61882,10 @@ static int defragmentPage(MemPage *pPage, int nMaxFrag){ if( cbrk==pc ) continue; temp = sqlite3PagerTempSpace(pPage->pBt->pPager); x = get2byte(&data[hdr+5]); - memcpy(&temp[x], &data[x], (cbrk+size) - x); + memmove(&temp[x], &data[x], (cbrk+size) - x); src = temp; } - memcpy(&data[cbrk], &src[pc], size); + memmove(&data[cbrk], &src[pc], size); } data[hdr+7] = 0; @@ -61944,7 +61944,7 @@ static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){ /* Remove the slot from the free-list. Update the number of ** fragmented bytes within the page. */ - memcpy(&aData[iAddr], &aData[pc], 2); + memmove(&aData[iAddr], &aData[pc], 2); aData[hdr+7] += (u8)x; }else{ /* The slot remains on the free-list. Reduce its size to account @@ -62733,7 +62733,7 @@ SQLITE_PRIVATE int sqlite3BtreeOpen( return SQLITE_NOMEM_BKPT; } if( isMemdb ){ - memcpy(zFullPathname, zFilename, nFilename); + memmove(zFullPathname, zFilename, nFilename); }else{ rc = sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname); @@ -63617,7 +63617,7 @@ static int newDatabase(BtShared *pBt){ data = pP1->aData; rc = sqlite3PagerWrite(pP1->pDbPage); if( rc ) return rc; - memcpy(data, zMagicHeader, sizeof(zMagicHeader)); + memmove(data, zMagicHeader, sizeof(zMagicHeader)); assert( sizeof(zMagicHeader)==16 ); data[16] = (u8)((pBt->pageSize>>8)&0xff); data[17] = (u8)((pBt->pageSize>>16)&0xff); @@ -64968,10 +64968,10 @@ static int copyPayload( if( rc!=SQLITE_OK ){ return rc; } - memcpy(pPayload, pBuf, nByte); + memmove(pPayload, pBuf, nByte); }else{ /* Copy data from page to buffer (a read operation) */ - memcpy(pBuf, pPayload, nByte); + memmove(pBuf, pPayload, nByte); } return SQLITE_OK; } @@ -65155,10 +65155,10 @@ static int accessPayload( u8 aSave[4]; u8 *aWrite = &pBuf[-4]; assert( aWrite>=pBufStart ); /* due to (6) */ - memcpy(aSave, aWrite, 4); + memmove(aSave, aWrite, 4); rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); nextPage = get4byte(aWrite); - memcpy(aWrite, aSave, 4); + memmove(aWrite, aSave, 4); }else #endif @@ -66238,7 +66238,7 @@ static int allocateBtreePage( goto end_allocate_page; } *pPgno = iTrunk; - memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); + memmove(&pPage1->aData[32], &pTrunk->aData[0], 4); *ppPage = pTrunk; pTrunk = 0; TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); @@ -66262,13 +66262,13 @@ static int allocateBtreePage( } if( k==0 ){ if( !pPrevTrunk ){ - memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); + memmove(&pPage1->aData[32], &pTrunk->aData[0], 4); }else{ rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); if( rc!=SQLITE_OK ){ goto end_allocate_page; } - memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4); + memmove(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4); } }else{ /* The trunk page is required by the caller but it contains @@ -66291,9 +66291,9 @@ static int allocateBtreePage( releasePage(pNewTrunk); goto end_allocate_page; } - memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4); + memmove(&pNewTrunk->aData[0], &pTrunk->aData[0], 4); put4byte(&pNewTrunk->aData[4], k-1); - memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); + memmove(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); releasePage(pNewTrunk); if( !pPrevTrunk ){ assert( sqlite3PagerIswriteable(pPage1->pDbPage) ); @@ -66358,7 +66358,7 @@ static int allocateBtreePage( rc = sqlite3PagerWrite(pTrunk->pDbPage); if( rc ) goto end_allocate_page; if( closestpDbPage) ); if( nSrc>=n ){ - memcpy(pPayload, pSrc, n); + memmove(pPayload, pSrc, n); }else if( nSrc>0 ){ n = nSrc; - memcpy(pPayload, pSrc, n); + memmove(pPayload, pSrc, n); }else{ memset(pPayload, 0, n); } @@ -66951,7 +66951,7 @@ static void insertCell( assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) ); if( pPage->nOverflow || sz+2>pPage->nFree ){ if( pTemp ){ - memcpy(pTemp, pCell, sz); + memmove(pTemp, pCell, sz); pCell = pTemp; } if( iChild ){ @@ -66989,7 +66989,7 @@ static void insertCell( assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB ); assert( idx+sz <= (int)pPage->pBt->usableSize ); pPage->nFree -= (u16)(2 + sz); - memcpy(&data[idx], pCell, sz); + memmove(&data[idx], pCell, sz); if( iChild ){ put4byte(&data[idx], iChild); } @@ -67086,7 +67086,7 @@ static int rebuildPage( u8 *pData; i = get2byte(&aData[hdr+5]); - memcpy(&pTmp[i], &aData[i], usableSize - i); + memmove(&pTmp[i], &aData[i], usableSize - i); pData = pEnd; for(i=0; ixCellSize(pPg, pCell) || CORRUPT_DB ); testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) ); } @@ -67164,7 +67164,7 @@ static int pageInsertArray( } /* pSlot and pCArray->apCell[i] will never overlap on a well-formed ** database. But they might for a corrupt database. Hence use memmove() - ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */ + ** since memmove() sends SIGABORT with overlapping buffers on OpenBSD */ assert( (pSlot+sz)<=pCArray->apCell[i] || pSlot>=(pCArray->apCell[i]+sz) || CORRUPT_DB ); @@ -67261,7 +67261,7 @@ static int editPage( #ifdef SQLITE_DEBUG u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); - memcpy(pTmp, aData, pPg->pBt->usableSize); + memmove(pTmp, aData, pPg->pBt->usableSize); #endif /* Remove cells from the start and end of the page */ @@ -67537,8 +67537,8 @@ static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ /* Copy the b-tree node content from page pFrom to page pTo. */ iData = get2byte(&aFrom[iFromHdr+5]); - memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData); - memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell); + memmove(&aTo[iData], &aFrom[iData], pBt->usableSize-iData); + memmove(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell); /* Reinitialize page pTo so that the contents of the MemPage structure ** match the new data. The initialization of pTo can actually fail under @@ -67732,7 +67732,7 @@ static int balance_nonroot( memset(apOld, 0, (i+1)*sizeof(MemPage*)); goto balance_cleanup; }else{ - memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); + memmove(&aOvflSpace[iOff], apDiv[i], szNew[i]); apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; } } @@ -67846,7 +67846,7 @@ static int balance_nonroot( iSpace1 += sz; assert( sz<=pBt->maxLocal+23 ); assert( iSpace1 <= (int)pBt->pageSize ); - memcpy(pTemp, apDiv[i], sz); + memmove(pTemp, apDiv[i], sz); b.apCell[b.nCell] = pTemp+leafCorrection; assert( leafCorrection==0 || leafCorrection==4 ); b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection; @@ -67855,7 +67855,7 @@ static int balance_nonroot( assert( pOld->hdrOffset==0 ); /* The right pointer of the child page pOld becomes the left ** pointer of the divider cell */ - memcpy(b.apCell[b.nCell], &pOld->aData[8], 4); + memmove(b.apCell[b.nCell], &pOld->aData[8], 4); }else{ assert( leafCorrection==4 ); while( b.szCell[b.nCell]<4 ){ @@ -68093,7 +68093,7 @@ static int balance_nonroot( ** originally in the same field of the right-most old sibling page. */ if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){ MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1]; - memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4); + memmove(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4); } /* Make any required updates to pointer map entries associated with @@ -68167,7 +68167,7 @@ static int balance_nonroot( sz = b.szCell[j] + leafCorrection; pTemp = &aOvflSpace[iOvflSpace]; if( !pNew->leaf ){ - memcpy(&pNew->aData[8], pCell, 4); + memmove(&pNew->aData[8], pCell, 4); }else if( leafData ){ /* If the tree is a leaf-data tree, and the siblings are leaves, ** then there is no divider cell in b.apCell[]. Instead, the divider @@ -68395,9 +68395,9 @@ static int balance_deeper(MemPage *pRoot, MemPage **ppChild){ TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno)); /* Copy the overflow cells from pRoot to pChild */ - memcpy(pChild->aiOvfl, pRoot->aiOvfl, + memmove(pChild->aiOvfl, pRoot->aiOvfl, pRoot->nOverflow*sizeof(pRoot->aiOvfl[0])); - memcpy(pChild->apOvfl, pRoot->apOvfl, + memmove(pChild->apOvfl, pRoot->apOvfl, pRoot->nOverflow*sizeof(pRoot->apOvfl[0])); pChild->nOverflow = pRoot->nOverflow; @@ -68684,7 +68684,7 @@ SQLITE_PRIVATE int sqlite3BtreeInsert( } oldCell = findCell(pPage, idx); if( !pPage->leaf ){ - memcpy(newCell, oldCell, 4); + memmove(newCell, oldCell, 4); } rc = clearCell(pPage, oldCell, &info); if( info.nSize==szNew && info.nLocal==info.nPayload @@ -68701,7 +68701,7 @@ SQLITE_PRIVATE int sqlite3BtreeInsert( ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */ assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */ if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT; - memcpy(oldCell, newCell, szNew); + memmove(oldCell, newCell, szNew); return SQLITE_OK; } dropCell(pPage, idx, info.nSize, &rc); @@ -68757,7 +68757,7 @@ SQLITE_PRIVATE int sqlite3BtreeInsert( if( pCur->pKey==0 ){ rc = SQLITE_NOMEM; }else{ - memcpy(pCur->pKey, pX->pKey, pX->nKey); + memmove(pCur->pKey, pX->pKey, pX->nKey); } } pCur->eState = CURSOR_REQUIRESEEK; @@ -70687,7 +70687,7 @@ static int backupOnePage( ** cached parse of the page). MemPage.isInit is marked ** "MUST BE FIRST" for this purpose. */ - memcpy(zOut, zIn, nCopy); + memmove(zOut, zIn, nCopy); ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0; if( iOff==0 && bUpdate==0 ){ sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc)); @@ -71363,7 +71363,7 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPre if( bPreserve && pMem->z ){ assert( pMem->z!=pMem->zMalloc ); - memcpy(pMem->zMalloc, pMem->z, pMem->n); + memmove(pMem->zMalloc, pMem->z, pMem->n); } if( (pMem->flags&MEM_Dyn)!=0 ){ assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC ); @@ -71556,7 +71556,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){ pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */ assert( (pMem->flags & MEM_Dyn)==0 ); if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc); - memcpy(pMem, &t, sizeof(t)); + memmove(pMem, &t, sizeof(t)); return ctx.isError; } @@ -72033,7 +72033,7 @@ SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int sr assert( (pFrom->flags & MEM_RowSet)==0 ); assert( pTo->db==pFrom->db ); if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; } - memcpy(pTo, pFrom, MEMCELLSIZE); + memmove(pTo, pFrom, MEMCELLSIZE); if( (pFrom->flags&MEM_Static)==0 ){ pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem); assert( srcType==MEM_Ephem || srcType==MEM_Static ); @@ -72050,7 +72050,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){ assert( (pFrom->flags & MEM_RowSet)==0 ); if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo); - memcpy(pTo, pFrom, MEMCELLSIZE); + memmove(pTo, pFrom, MEMCELLSIZE); pTo->flags &= ~MEM_Dyn; if( pTo->flags&(MEM_Str|MEM_Blob) ){ if( 0==(pFrom->flags&MEM_Static) ){ @@ -72074,7 +72074,7 @@ SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){ assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db ); sqlite3VdbeMemRelease(pTo); - memcpy(pTo, pFrom, sizeof(Mem)); + memmove(pTo, pFrom, sizeof(Mem)); pFrom->flags = MEM_Null; pFrom->szMalloc = 0; } @@ -72149,7 +72149,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr( if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){ return SQLITE_NOMEM_BKPT; } - memcpy(pMem->z, z, nAlloc); + memmove(pMem->z, z, nAlloc); }else if( xDel==SQLITE_DYNAMIC ){ sqlite3VdbeMemRelease(pMem); pMem->zMalloc = pMem->z = (char *)z; @@ -73047,7 +73047,7 @@ SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ pB->zSql = zTmp; pB->expmask = pA->expmask; pB->prepFlags = pA->prepFlags; - memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter)); + memmove(pB->aCounter, pA->aCounter, sizeof(pB->aCounter)); pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++; } @@ -73259,7 +73259,7 @@ SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8( int p4type /* P4 operand type */ ){ char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8); - if( p4copy ) memcpy(p4copy, zP4, 8); + if( p4copy ) memmove(p4copy, zP4, 8); return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type); } @@ -76327,7 +76327,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){ u32 i; if( serial_type==7 ){ assert( sizeof(v)==sizeof(pMem->u.r) ); - memcpy(&v, &pMem->u.r, sizeof(v)); + memmove(&v, &pMem->u.r, sizeof(v)); swapMixedEndianFloat(v); }else{ v = pMem->u.i; @@ -76346,7 +76346,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){ assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0) == (int)sqlite3VdbeSerialTypeLen(serial_type) ); len = pMem->n; - if( len>0 ) memcpy(buf, pMem->z, len); + if( len>0 ) memmove(buf, pMem->z, len); return len; } @@ -76403,7 +76403,7 @@ static u32 SQLITE_NOINLINE serialGet( #endif assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 ); swapMixedEndianFloat(x); - memcpy(&pMem->u.r, &x, sizeof(x)); + memmove(&pMem->u.r, &x, sizeof(x)); pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real; } return 8; @@ -77986,7 +77986,7 @@ SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){ pNew = sqlite3_malloc( sizeof(*pNew) ); if( pNew==0 ) return 0; memset(pNew, 0, sizeof(*pNew)); - memcpy(pNew, pOrig, MEMCELLSIZE); + memmove(pNew, pOrig, MEMCELLSIZE); pNew->flags &= ~MEM_Dyn; pNew->db = 0; if( pNew->flags&(MEM_Str|MEM_Blob) ){ @@ -81382,7 +81382,7 @@ case OP_ResultRow: { ** ** It is illegal for P1 and P3 to be the same register. Sometimes, ** if P3 is the same register as P2, the implementation is able -** to avoid a memcpy(). +** to avoid a memmove(). */ case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ i64 nByte; @@ -81407,9 +81407,9 @@ case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ } MemSetTypeFlag(pOut, MEM_Str); if( pOut!=pIn2 ){ - memcpy(pOut->z, pIn2->z, pIn2->n); + memmove(pOut->z, pIn2->z, pIn2->n); } - memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n); + memmove(&pOut->z[pIn2->n], pIn1->z, pIn1->n); pOut->z[nByte]=0; pOut->z[nByte+1] = 0; pOut->flags |= MEM_Term; @@ -81636,7 +81636,7 @@ case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ if( iB>=64 ){ iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1; }else{ - memcpy(&uA, &iA, sizeof(uA)); + memmove(&uA, &iA, sizeof(uA)); if( op==OP_ShiftLeft ){ uA <<= iB; }else{ @@ -81644,7 +81644,7 @@ case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ /* Sign-extend on a right shift of a negative number */ if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB); } - memcpy(&iA, &uA, sizeof(iA)); + memmove(&iA, &uA, sizeof(iA)); } } pOut->u.i = iA; @@ -82602,7 +82602,7 @@ case OP_Column: { }else{ pDest->z = pDest->zMalloc; } - memcpy(pDest->z, zData, len); + memmove(pDest->z, zData, len); pDest->z[len] = 0; pDest->z[len+1] = 0; pDest->flags = aFlag[t&1]; @@ -82934,7 +82934,7 @@ case OP_Savepoint: { pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1); if( pNew ){ pNew->zName = (char *)&pNew[1]; - memcpy(pNew->zName, zName, nName+1); + memmove(pNew->zName, zName, nName+1); /* If there is no open transaction, then mark this as a special ** "transaction savepoint". */ @@ -88348,7 +88348,7 @@ static int vdbePmaReadBlob( /* Copy as much data as is available in the buffer into the start of ** p->aAlloc[]. */ - memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail); + memmove(p->aAlloc, &p->aBuffer[iBuf], nAvail); p->iReadOff += nAvail; nRem = nByte - nAvail; @@ -88364,7 +88364,7 @@ static int vdbePmaReadBlob( rc = vdbePmaReadBlob(p, nCopy, &aNext); if( rc!=SQLITE_OK ) return rc; assert( aNext!=p->aAlloc ); - memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy); + memmove(&p->aAlloc[nByte - nRem], aNext, nCopy); nRem -= nCopy; } @@ -88770,7 +88770,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit( rc = SQLITE_NOMEM_BKPT; }else{ pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz); - memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo); + memmove(pKeyInfo, pCsr->pKeyInfo, szKeyInfo); pKeyInfo->db = 0; if( nField && nWorker==0 ){ pKeyInfo->nKeyField = nField; @@ -89278,7 +89278,7 @@ static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){ nCopy = p->nBuffer - p->iBufEnd; } - memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy); + memmove(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy); p->iBufEnd += nCopy; if( p->iBufEnd==p->nBuffer ){ p->eFWErr = sqlite3OsWrite(p->pFd, @@ -89655,7 +89655,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterWrite( pNew->u.pNext = pSorter->list.pList; } - memcpy(SRVAL(pNew), pVal->z, pVal->n); + memmove(SRVAL(pNew), pVal->z, pVal->n); pNew->nVal = pVal->n; pSorter->list.pList = pNew; @@ -90493,7 +90493,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){ } pOut->n = nKey; MemSetTypeFlag(pOut, MEM_Blob); - memcpy(pOut->z, pKey, nKey); + memmove(pOut->z, pKey, nKey); return SQLITE_OK; } @@ -90676,7 +90676,7 @@ static int memjrnlRead( do { int iSpace = p->nChunkSize - iChunkOffset; int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset)); - memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy); + memmove(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy); zOut += nCopy; nRead -= iSpace; iChunkOffset = 0; @@ -90774,7 +90774,7 @@ static int memjrnlWrite( || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) if( iOfst==0 && p->pFirst ){ assert( p->nChunkSize>iAmt ); - memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt); + memmove((u8*)p->pFirst->zChunk, zBuf, iAmt); }else #else assert( iOfst>0 || p->pFirst==0 ); @@ -90802,7 +90802,7 @@ static int memjrnlWrite( p->endpoint.pChunk = pNew; } - memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace); + memmove((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace); zWrite += iSpace; nWrite -= iSpace; p->endpoint.iOffset += iSpace; @@ -91237,14 +91237,14 @@ static void resolveAlias( /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This ** prevents ExprDelete() from deleting the Expr structure itself, - ** allowing it to be repopulated by the memcpy() on the following line. + ** allowing it to be repopulated by the memmove() on the following line. ** The pExpr->u.zToken might point into memory that will be freed by the ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to ** make a copy of the token before doing the sqlite3DbFree(). */ ExprSetProperty(pExpr, EP_Static); sqlite3ExprDelete(db, pExpr); - memcpy(pExpr, pDup, sizeof(*pExpr)); + memmove(pExpr, pDup, sizeof(*pExpr)); if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){ assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 ); pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken); @@ -93466,7 +93466,7 @@ SQLITE_PRIVATE Expr *sqlite3ExprAlloc( }else{ pNew->u.zToken = (char*)&pNew[1]; assert( pToken->z!=0 || pToken->n==0 ); - if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); + if( pToken->n ) memmove(pNew->u.zToken, pToken->z, pToken->n); pNew->u.zToken[pToken->n] = 0; if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){ if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted; @@ -93908,10 +93908,10 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ } if( dupFlags ){ assert( ExprHasProperty(p, EP_Reduced)==0 ); - memcpy(zAlloc, p, nNewSize); + memmove(zAlloc, p, nNewSize); }else{ u32 nSize = (u32)exprStructSize(p); - memcpy(zAlloc, p, nSize); + memmove(zAlloc, p, nSize); if( nSizeu.zToken string, if any. */ if( nToken ){ char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize]; - memcpy(zToken, p->u.zToken, nToken); + memmove(zToken, p->u.zToken, nToken); } if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){ @@ -98803,7 +98803,7 @@ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ assert( db->mallocFailed ); goto exit_begin_add_column; } - memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol); + memmove(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol); for(i=0; inCol; i++){ Column *pCol = &pNew->aCol[i]; pCol->zName = sqlite3DbStrDup(db, pCol->zName); @@ -99151,7 +99151,7 @@ static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){ p->u.aRowid = sqlite3DbMallocRawNN(db, n); if( p->u.aRowid ){ p->nRowid = n; - memcpy(p->u.aRowid, pData, n); + memmove(p->u.aRowid, pData, n); }else{ p->nRowid = 0; } @@ -99178,9 +99178,9 @@ static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){ pTo->isPSample = pFrom->isPSample; pTo->iCol = pFrom->iCol; pTo->iHash = pFrom->iHash; - memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol); - memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol); - memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol); + memmove(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol); + memmove(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol); + memmove(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol); if( pFrom->nRowid ){ sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid); }else{ @@ -99865,7 +99865,7 @@ static void analyzeOneTable( pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13); if( pStat1==0 ) return; pStat1->zName = (char*)&pStat1[1]; - memcpy(pStat1->zName, "sqlite_stat1", 13); + memmove(pStat1->zName, "sqlite_stat1", 13); pStat1->nCol = 3; pStat1->iPKey = -1; sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB); @@ -100639,7 +100639,7 @@ static int loadStatTbl( return SQLITE_NOMEM_BKPT; } if( pSample->n ){ - memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n); + memmove(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n); } pIdx->nSample++; } @@ -100877,7 +100877,7 @@ static void attachFunc( if( db->aDb==db->aDbStatic ){ aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 ); if( aNew==0 ) return; - memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2); + memmove(aNew, db->aDb, sizeof(db->aDb[0])*2); }else{ aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) ); if( aNew==0 ) return; @@ -101882,12 +101882,12 @@ SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ return; /* A malloc must have failed */ } pParse->nested++; - memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ); + memmove(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ); memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ); sqlite3RunParser(pParse, zSql, &zErrMsg); sqlite3DbFree(db, zErrMsg); sqlite3DbFree(db, zSql); - memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ); + memmove(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ); pParse->nested--; } @@ -102124,7 +102124,7 @@ SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){ } db->nDb = j; if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ - memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); + memmove(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); sqlite3DbFree(db, db->aDb); db->aDb = db->aDbStatic; } @@ -102687,7 +102687,7 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){ } z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2); if( z==0 ) return; - memcpy(z, pName->z, pName->n); + memmove(z, pName->z, pName->n); z[pName->n] = 0; sqlite3Dequote(z); for(i=0; inCol; i++){ @@ -102718,7 +102718,7 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){ pCol->szEst = 1; }else{ zType = z + sqlite3Strlen30(z) + 1; - memcpy(zType, pType->z, pType->n); + memmove(zType, pType->z, pType->n); zType[pType->n] = 0; sqlite3Dequote(zType); pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst); @@ -103216,7 +103216,7 @@ static char *createTableStmt(sqlite3 *db, Table *p){ len = sqlite3Strlen30(zType); assert( pCol->affinity==SQLITE_AFF_BLOB || pCol->affinity==sqlite3AffinityType(zType, 0) ); - memcpy(&zStmt[k], zType, len); + memmove(&zStmt[k], zType, len); k += len; assert( k<=n ); } @@ -103236,13 +103236,13 @@ static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ nByte = (sizeof(char*) + sizeof(i16) + 1)*N; zExtra = sqlite3DbMallocZero(db, nByte); if( zExtra==0 ) return SQLITE_NOMEM_BKPT; - memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); + memmove(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); pIdx->azColl = (const char**)zExtra; zExtra += sizeof(char*)*N; - memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); + memmove(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); pIdx->aiColumn = (i16*)zExtra; zExtra += sizeof(i16)*N; - memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); + memmove(zExtra, pIdx->aSortOrder, pIdx->nColumn); pIdx->aSortOrder = (u8*)zExtra; pIdx->nColumn = N; pIdx->isResized = 1; @@ -104295,7 +104295,7 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey( pFKey->pNextFrom = p->pFKey; z = (char*)&pFKey->aCol[nCol]; pFKey->zTo = z; - memcpy(z, pTo->z, pTo->n); + memmove(z, pTo->z, pTo->n); z[pTo->n] = 0; sqlite3Dequote(z); z += pTo->n+1; @@ -104323,7 +104323,7 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey( for(i=0; ia[i].zName); pFKey->aCol[i].zCol = z; - memcpy(z, pToCol->a[i].zName, n); + memmove(z, pToCol->a[i].zName, n); z[n] = 0; z += n+1; } @@ -104738,7 +104738,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex( assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); pIndex->zName = zExtra; zExtra += nName + 1; - memcpy(pIndex->zName, zName, nName+1); + memmove(pIndex->zName, zName, nName+1); pIndex->pTable = pTab; pIndex->onError = (u8)onError; pIndex->uniqNotNull = onError!=OE_None; @@ -104811,7 +104811,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex( zColl = pListItem->pExpr->u.zToken; nColl = sqlite3Strlen30(zColl) + 1; assert( nExtra>=nColl ); - memcpy(zExtra, zColl, nColl); + memmove(zExtra, zColl, nColl); zColl = zExtra; zExtra += nColl; nExtra -= nColl; @@ -105090,7 +105090,7 @@ SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){ /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is ** 6 and each subsequent value (if any) is 5. */ - memcpy(&a[1], aVal, nCopy*sizeof(LogEst)); + memmove(&a[1], aVal, nCopy*sizeof(LogEst)); for(i=nCopy+1; i<=pIdx->nKeyCol; i++){ a[i] = 23; assert( 23==sqlite3LogEst(5) ); } @@ -106135,7 +106135,7 @@ static int synthCollSeq(sqlite3 *db, CollSeq *pColl){ for(i=0; i<3; i++){ pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0); if( pColl2->xCmp!=0 ){ - memcpy(pColl, pColl2, sizeof(CollSeq)); + memmove(pColl, pColl2, sizeof(CollSeq)); pColl->xDel = 0; /* Do not copy the destructor */ return SQLITE_OK; } @@ -106246,7 +106246,7 @@ static CollSeq *findCollSeqEntry( pColl[1].enc = SQLITE_UTF16LE; pColl[2].zName = (char*)&pColl[3]; pColl[2].enc = SQLITE_UTF16BE; - memcpy(pColl[0].zName, zName, nName); + memmove(pColl[0].zName, zName, nName); pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl); /* If a malloc() failure occurred in sqlite3HashInsert(), it will @@ -106487,7 +106487,7 @@ SQLITE_PRIVATE FuncDef *sqlite3FindFunction( pBest->zName = (const char*)&pBest[1]; pBest->nArg = (u16)nArg; pBest->funcFlags = enc; - memcpy((char*)&pBest[1], zName, nName+1); + memmove((char*)&pBest[1], zName, nName+1); pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest); if( pOther==pBest ){ sqlite3DbFree(db, pBest); @@ -108760,13 +108760,13 @@ static void replaceFunc( sqlite3_free(zOld); return; } - memcpy(&zOut[j], zRep, nRep); + memmove(&zOut[j], zRep, nRep); j += nRep; i += nPattern-1; } } assert( j+nStr-i+1==nOut ); - memcpy(&zOut[j], &zStr[i], nStr-i); + memmove(&zOut[j], &zStr[i], nStr-i); j += nStr - i; assert( j<=nOut ); zOut[j] = 0; @@ -109261,11 +109261,11 @@ SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocas aWc[3] = zEscape[0]; } - /* The memcpy() statement assumes that the wildcard characters are + /* The memmove() statement assumes that the wildcard characters are ** the first three statements in the compareInfo structure. The ** asserts() that follow verify that assumption */ - memcpy(aWc, pDef->pUserData, 3); + memmove(aWc, pDef->pUserData, 3); assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll ); assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne ); assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet ); @@ -110712,7 +110712,7 @@ static Trigger *fkActionTrigger( if( pTrigger ){ pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1]; pStep->zTarget = (char *)&pStep[1]; - memcpy((char *)pStep->zTarget, zFrom, nFrom); + memmove((char *)pStep->zTarget, zFrom, nFrom); pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE); @@ -114373,7 +114373,7 @@ static int sqlite3LoadExtension( sqlite3OsDlClose(pVfs, handle); return SQLITE_NOMEM_BKPT; } - memcpy(zAltEntry, "sqlite3_", 8); + memmove(zAltEntry, "sqlite3_", 8); for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){} iFile++; if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3; @@ -114382,7 +114382,7 @@ static int sqlite3LoadExtension( zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c]; } } - memcpy(zAltEntry+iEntry, "_init", 6); + memmove(zAltEntry+iEntry, "_init", 6); zEntry = zAltEntry; xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry); } @@ -114418,7 +114418,7 @@ static int sqlite3LoadExtension( return SQLITE_NOMEM_BKPT; } if( db->nExtension>0 ){ - memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension); + memmove(aHandle, db->aExtension, sizeof(handle)*db->nExtension); } sqlite3DbFree(db, db->aExtension); db->aExtension = aHandle; @@ -120487,7 +120487,7 @@ SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation( n = sqlite3Strlen30(pCol->zName); pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2); if( pCol->zName ){ - memcpy(&pCol->zName[n+1], zType, m+1); + memmove(&pCol->zName[n+1], zType, m+1); pCol->colFlags |= COLFLAG_HASTYPE; } } @@ -124827,7 +124827,7 @@ static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){ int n = sqlite3Strlen30(argv[i])+1; z = sqlite3_malloc64( n ); if( z==0 ) goto malloc_failed; - memcpy(z, argv[i], n); + memmove(z, argv[i], n); } p->azResult[p->nData++] = z; } @@ -125332,7 +125332,7 @@ static TriggerStep *triggerStepAllocate( pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1); if( pTriggerStep ){ char *z = (char*)&pTriggerStep[1]; - memcpy(z, pName->z, pName->n); + memmove(z, pName->z, pName->n); sqlite3Dequote(z); pTriggerStep->zTarget = z; pTriggerStep->op = op; @@ -127407,7 +127407,7 @@ SQLITE_PRIVATE Module *sqlite3VtabCreateModule( }else{ Module *pDel; char *zCopy = (char *)(&pMod[1]); - memcpy(zCopy, zName, nName+1); + memmove(zCopy, zName, nName+1); pMod->zName = zCopy; pMod->pModule = pModule; pMod->pAux = pAux; @@ -128448,7 +128448,7 @@ SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction( } *pNew = *pDef; pNew->zName = (const char*)&pNew[1]; - memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1); + memmove((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1); pNew->xSFunc = xSFunc; pNew->pUserData = pArg; pNew->funcFlags |= SQLITE_FUNC_EPHEM; @@ -131012,10 +131012,10 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( if( pOrTab==0 ) return notReady; pOrTab->nAlloc = (u8)(nNotReady + 1); pOrTab->nSrc = pOrTab->nAlloc; - memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); + memmove(pOrTab->a, pTabItem, sizeof(*pTabItem)); origSrc = pWInfo->pTabList->a; for(k=1; k<=nNotReady; k++){ - memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); + memmove(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); } }else{ pOrTab = pWInfo->pTabList; @@ -131448,7 +131448,7 @@ static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){ pWC->a = pOld; return 0; } - memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); + memmove(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); if( pOld!=pWC->aStatic ){ sqlite3DbFree(db, pOld); } @@ -133021,7 +133021,7 @@ SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ ** unable to use the ONEPASS optimization. */ SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ - memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2); + memmove(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2); #ifdef WHERETRACE_ENABLED if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){ sqlite3DebugPrintf("%s cursors: %d %d\n", @@ -133037,7 +133037,7 @@ SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ */ static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){ pDest->n = pSrc->n; - memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0])); + memmove(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0])); } /* @@ -134615,7 +134615,7 @@ static void whereTermPrint(WhereTerm *pTerm, int iTerm){ }else{ char zType[4]; char zLeft[50]; - memcpy(zType, "...", 4); + memmove(zType, "...", 4); if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V'; if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E'; if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L'; @@ -134752,7 +134752,7 @@ static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){ n = (n+7)&~7; paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n); if( paNew==0 ) return SQLITE_NOMEM_BKPT; - memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot); + memmove(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot); if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm); p->aLTerm = paNew; p->nLSlot = n; @@ -134768,8 +134768,8 @@ static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ memset(&pTo->u, 0, sizeof(pTo->u)); return SQLITE_NOMEM_BKPT; } - memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ); - memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0])); + memmove(pTo, pFrom, WHERE_LOOP_XFER_SZ); + memmove(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0])); if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){ pFrom->u.vtab.needFree = 0; }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){ @@ -137045,7 +137045,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ pTo->rCost = rCost; pTo->rUnsorted = rUnsorted; pTo->isOrdered = isOrdered; - memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop); + memmove(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop); pTo->aLoop[iLoop] = pWLoop; if( nTo>=mxChoice ){ mxI = 0; @@ -138230,7 +138230,7 @@ static void disableLookaside(Parse *pParse){ p->flags = EP_Leaf; p->iAgg = -1; p->u.zToken = (char*)&p[1]; - memcpy(p->u.zToken, t.z, t.n); + memmove(p->u.zToken, t.z, t.n); p->u.zToken[t.n] = 0; if( sqlite3Isquote(p->u.zToken[0]) ){ if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted; @@ -143641,7 +143641,7 @@ SQLITE_API int sqlite3_initialize(void){ double y; assert(sizeof(x)==8); assert(sizeof(x)==sizeof(y)); - memcpy(&y, &x, 8); + memmove(&y, &x, 8); assert( sqlite3IsNaN(y) ); } #endif @@ -146131,7 +146131,7 @@ SQLITE_PRIVATE int sqlite3ParseUri( zFile = sqlite3_malloc64(nUri+2); if( !zFile ) return SQLITE_NOMEM_BKPT; if( nUri ){ - memcpy(zFile, zUri, nUri); + memmove(zFile, zUri, nUri); } zFile[nUri] = '\0'; zFile[nUri+1] = '\0'; @@ -146244,7 +146244,7 @@ static int openDatabase( db->aDb = db->aDbStatic; assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); - memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); + memmove(db->aLimit, aHardLimit, sizeof(db->aLimit)); db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS; db->autoCommit = 1; db->nextAutovac = -1; @@ -147818,7 +147818,7 @@ SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){ /* The aArg[] array needs to grow. */ void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2); if( pNew ){ - memcpy(pNew, aArg, nArg*sizeof(void *)); + memmove(pNew, aArg, nArg*sizeof(void *)); sqlite3_free(aDyn); aDyn = aArg = pNew; }else{ @@ -149880,7 +149880,7 @@ static int fts3ContentColumns( for(i=0; imxSavepoint = -1 ); p->aIndex = (struct Fts3Index *)&p->azColumn[nCol]; - memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex); + memmove(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex); p->nIndex = nIndex; for(i=0; iaIndex[i].hPending, FTS3_HASH_STRING, 1); @@ -150187,10 +150187,10 @@ static int fts3InitVtab( /* Fill in the zName and zDb fields of the vtab structure. */ zCsr = (char *)&p->abNotindexed[nCol]; p->zName = zCsr; - memcpy(zCsr, argv[2], nName); + memmove(zCsr, argv[2], nName); zCsr += nName; p->zDb = zCsr; - memcpy(zCsr, argv[1], nDb); + memmove(zCsr, argv[1], nDb); zCsr += nDb; /* Fill in the azColumn array */ @@ -150199,7 +150199,7 @@ static int fts3InitVtab( int n = 0; z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n); if( n>0 ){ - memcpy(zCsr, z, n); + memmove(zCsr, z, n); } zCsr[n] = '\0'; sqlite3Fts3Dequote(zCsr); @@ -150671,7 +150671,7 @@ static int fts3ScanInteriorNode( zBuffer = zNew; } assert( zBuffer ); - memcpy(&zBuffer[nPrefix], zCsr, nSuffix); + memmove(&zBuffer[nPrefix], zCsr, nSuffix); nBuffer = nPrefix + nSuffix; zCsr += nSuffix; @@ -150823,7 +150823,7 @@ static void fts3PoslistCopy(char **pp, char **ppPoslist){ if( pp ){ int n = (int)(pEnd - *ppPoslist); char *p = *pp; - memcpy(p, *ppPoslist, n); + memmove(p, *ppPoslist, n); p += n; *pp = p; } @@ -150861,7 +150861,7 @@ static void fts3ColumnlistCopy(char **pp, char **ppPoslist){ if( pp ){ int n = (int)(pEnd - *ppPoslist); char *p = *pp; - memcpy(p, *ppPoslist, n); + memmove(p, *ppPoslist, n); p += n; *pp = p; } @@ -151560,7 +151560,7 @@ static int fts3TermSelectMerge( ){ if( pTS->aaOutput[0]==0 ){ /* If this is the first term selected, copy the doclist to the output - ** buffer using memcpy(). + ** buffer using memmove(). ** ** Add FTS3_VARINT_MAX bytes of unused space to the end of the ** allocation. This is so as to ensure that the buffer is big enough @@ -151578,7 +151578,7 @@ static int fts3TermSelectMerge( pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1); pTS->anOutput[0] = nDoclist; if( pTS->aaOutput[0] ){ - memcpy(pTS->aaOutput[0], aDoclist, nDoclist); + memmove(pTS->aaOutput[0], aDoclist, nDoclist); }else{ return SQLITE_NOMEM; } @@ -153396,7 +153396,7 @@ static int fts3EvalIncrPhraseNext( int nByte = a[p->nToken-1].nList; char *aDoclist = sqlite3_malloc(nByte+1); if( !aDoclist ) return SQLITE_NOMEM; - memcpy(aDoclist, a[p->nToken-1].pList, nByte+1); + memmove(aDoclist, a[p->nToken-1].pList, nByte+1); for(i=0; i<(p->nToken-1); i++){ if( a[i].bIgnore==0 ){ @@ -154867,8 +154867,8 @@ static int fts3auxConnectMethod( p->pFts3Tab->db = db; p->pFts3Tab->nIndex = 1; - memcpy((char *)p->pFts3Tab->zDb, zDb, nDb); - memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3); + memmove((char *)p->pFts3Tab->zDb, zDb, nDb); + memmove((char *)p->pFts3Tab->zName, zFts3, nFts3); sqlite3Fts3Dequote((char *)p->pFts3Tab->zName); *ppVtab = (sqlite3_vtab *)p; @@ -155525,7 +155525,7 @@ static int getNextToken( pRet->pPhrase->iColumn = iCol; pRet->pPhrase->aToken[0].n = nToken; pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1]; - memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken); + memmove(pRet->pPhrase->aToken[0].z, zToken, nToken); if( iEndpPhrase->aToken[0].isPrefix = 1; @@ -155640,7 +155640,7 @@ static int getNextString( pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii]; memset(pToken, 0, sizeof(Fts3PhraseToken)); - memcpy(&zTemp[nTemp], zByte, nByte); + memmove(&zTemp[nTemp], zByte, nByte); nTemp += nByte; pToken->n = nByte; @@ -155668,7 +155668,7 @@ static int getNextString( zBuf = (char *)&p->pPhrase->aToken[nToken]; if( zTemp ){ - memcpy(zBuf, zTemp, nTemp); + memmove(zBuf, zTemp, nTemp); sqlite3_free(zTemp); }else{ assert( nTemp==0 ); @@ -156441,7 +156441,7 @@ static int queryTestTokenizer( sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); if( SQLITE_ROW==sqlite3_step(pStmt) ){ if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ - memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); + memmove((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); } } @@ -156990,7 +156990,7 @@ SQLITE_PRIVATE void *sqlite3Fts3HashInsert( fts3HashFree(new_elem); return data; } - memcpy((void*)new_elem->pKey, pKey, nKey); + memmove((void*)new_elem->pKey, pKey, nKey); }else{ new_elem->pKey = (void*)pKey; } @@ -158064,7 +158064,7 @@ int queryTokenizer( sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); if( SQLITE_ROW==sqlite3_step(pStmt) ){ if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ - memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); + memmove((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); } } @@ -158561,7 +158561,7 @@ static int fts3tokDequoteArray( for(i=0; izInput==0 ){ rc = SQLITE_NOMEM; }else{ - memcpy(pCsr->zInput, zByte, nByte); + memmove(pCsr->zInput, zByte, nByte); pCsr->zInput[nByte] = 0; rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr); if( rc==SQLITE_OK ){ @@ -160222,7 +160222,7 @@ static int fts3SegReaderNext( pReader->nTerm = fts3HashKeysize(pElem); aCopy = (char*)sqlite3_malloc(nCopy); if( !aCopy ) return SQLITE_NOMEM; - memcpy(aCopy, pList->aData, nCopy); + memmove(aCopy, pList->aData, nCopy); pReader->nNode = pReader->nDoclist = nCopy; pReader->aNode = pReader->aDoclist = aCopy; pReader->ppNextElem++; @@ -160281,7 +160281,7 @@ static int fts3SegReaderNext( rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX); if( rc!=SQLITE_OK ) return rc; - memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix); + memmove(&pReader->zTerm[nPrefix], pNext, nSuffix); pReader->nTerm = nPrefix+nSuffix; pNext += nSuffix; pNext += fts3GetVarint32(pNext, &pReader->nDoclist); @@ -160513,7 +160513,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderNew( pReader->aNode = (char *)&pReader[1]; pReader->rootOnly = 1; pReader->nNode = nRoot; - memcpy(pReader->aNode, zRoot, nRoot); + memmove(pReader->aNode, zRoot, nRoot); memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING); }else{ pReader->iCurrentBlock = iStartLeaf-1; @@ -160636,7 +160636,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderPending( memset(pReader, 0, nByte); pReader->iIdx = 0x7FFFFFFF; pReader->ppNextElem = (Fts3HashElem **)&pReader[1]; - memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *)); + memmove(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *)); } } @@ -160927,7 +160927,7 @@ static int fts3NodeAddTerm( } nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix); - memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix); + memmove(&pTree->aData[nData], &zTerm[nPrefix], nSuffix); pTree->nData = nData + nSuffix; pTree->nEntry++; @@ -160941,7 +160941,7 @@ static int fts3NodeAddTerm( pTree->zMalloc = zNew; } pTree->zTerm = pTree->zMalloc; - memcpy(pTree->zTerm, zTerm, nTerm); + memmove(pTree->zTerm, zTerm, nTerm); pTree->nTerm = nTerm; }else{ pTree->zTerm = (char *)zTerm; @@ -161191,10 +161191,10 @@ static int fts3SegWriterAdd( /* Append the prefix-compressed term and doclist to the buffer. */ nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix); nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix); - memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix); + memmove(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix); nData += nSuffix; nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist); - memcpy(&pWriter->aData[nData], aDoclist, nDoclist); + memmove(&pWriter->aData[nData], aDoclist, nDoclist); pWriter->nData = nData + nDoclist; /* Save the current term so that it can be used to prefix-compress the next. @@ -161213,7 +161213,7 @@ static int fts3SegWriterAdd( pWriter->zTerm = zNew; } assert( pWriter->zTerm==pWriter->zMalloc ); - memcpy(pWriter->zTerm, zTerm, nTerm); + memmove(pWriter->zTerm, zTerm, nTerm); }else{ pWriter->zTerm = (char *)zTerm; } @@ -161521,7 +161521,7 @@ static int fts3MsrBufferData( pMsr->aBuffer = pNew; } - memcpy(pMsr->aBuffer, pList, nList); + memmove(pMsr->aBuffer, pList, nList); return SQLITE_OK; } @@ -161865,7 +161865,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStep( nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta); iPrev = iDocid; if( isRequirePos ){ - memcpy(&pCsr->aBuffer[nDoclist], pList, nList); + memmove(&pCsr->aBuffer[nDoclist], pList, nList); nDoclist += nList; pCsr->aBuffer[nDoclist++] = '\0'; } @@ -162617,7 +162617,7 @@ static int nodeReaderNext(NodeReader *p){ blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc); if( rc==SQLITE_OK ){ - memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix); + memmove(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix); p->term.n = nPrefix+nSuffix; p->iOff += nSuffix; if( p->iChild==0 ){ @@ -162721,10 +162721,10 @@ static int fts3IncrmergePush( pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix); } pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix); - memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix); + memmove(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix); pBlk->n += nSuffix; - memcpy(pNode->key.a, zTerm, nTerm); + memmove(pNode->key.a, zTerm, nTerm); pNode->key.n = nTerm; } }else{ @@ -162797,19 +162797,19 @@ static int fts3AppendToNode( nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm); nSuffix = nTerm - nPrefix; - memcpy(pPrev->a, zTerm, nTerm); + memmove(pPrev->a, zTerm, nTerm); pPrev->n = nTerm; if( bFirst==0 ){ pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix); } pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix); - memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix); + memmove(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix); pNode->n += nSuffix; if( aDoclist ){ pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist); - memcpy(&pNode->a[pNode->n], aDoclist, nDoclist); + memmove(&pNode->a[pNode->n], aDoclist, nDoclist); pNode->n += nDoclist; } @@ -163140,7 +163140,7 @@ static int fts3IncrmergeLoad( pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight; blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc); if( rc==SQLITE_OK ){ - memcpy(pNode->block.a, aRoot, nRoot); + memmove(pNode->block.a, aRoot, nRoot); pNode->block.n = nRoot; } @@ -163152,7 +163152,7 @@ static int fts3IncrmergeLoad( while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader); blobGrowBuffer(&pNode->key, reader.term.n, &rc); if( rc==SQLITE_OK ){ - memcpy(pNode->key.a, reader.term.a, reader.term.n); + memmove(pNode->key.a, reader.term.a, reader.term.n); pNode->key.n = reader.term.n; if( i>0 ){ char *aBlock = 0; @@ -163162,7 +163162,7 @@ static int fts3IncrmergeLoad( rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0); blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc); if( rc==SQLITE_OK ){ - memcpy(pNode->block.a, aBlock, nBlock); + memmove(pNode->block.a, aBlock, nBlock); pNode->block.n = nBlock; } sqlite3_free(aBlock); @@ -163626,7 +163626,7 @@ static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){ if( aHint ){ blobGrowBuffer(pHint, nHint, &rc); if( rc==SQLITE_OK ){ - memcpy(pHint->a, aHint, nHint); + memmove(pHint->a, aHint, nHint); pHint->n = nHint; } } @@ -164320,7 +164320,7 @@ SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList( *pnData = p->pList->nData - nSkip; *ppData = pRet; - memcpy(pRet, &p->pList->aData[nSkip], *pnData); + memmove(pRet, &p->pList->aData[nSkip], *pnData); return SQLITE_OK; } @@ -164713,7 +164713,7 @@ static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){ pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1); pRet->nElem = nElem; pRet->zMatchinfo = ((char*)pRet) + nByte; - memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1); + memmove(pRet->zMatchinfo, zMatchinfo, nStr+1); pRet->aRef[0] = 1; } @@ -164754,7 +164754,7 @@ static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){ aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32)); if( aOut ){ xRet = sqlite3_free; - if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32)); + if( p->bGlobal ) memmove(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32)); } } @@ -164764,7 +164764,7 @@ static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){ static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){ p->bGlobal = 1; - memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32)); + memmove(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32)); } /* @@ -165188,7 +165188,7 @@ static int fts3StringAppend( assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) ); /* Append the data to the string buffer. */ - memcpy(&pStr->z[pStr->n], zAppend, nAppend); + memmove(&pStr->z[pStr->n], zAppend, nAppend); pStr->n += nAppend; pStr->z[pStr->n] = '\0'; @@ -167485,15 +167485,15 @@ static void readCoord(u8 *p, RtreeCoord *pCoord){ static i64 readInt64(u8 *p){ #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 u64 x; - memcpy(&x, p, 8); + memmove(&x, p, 8); return (i64)_byteswap_uint64(x); #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 u64 x; - memcpy(&x, p, 8); + memmove(&x, p, 8); return (i64)__builtin_bswap64(x); #elif SQLITE_BYTEORDER==4321 i64 x; - memcpy(&x, p, 8); + memmove(&x, p, 8); return x; #else return (i64)( @@ -167525,13 +167525,13 @@ static int writeCoord(u8 *p, RtreeCoord *pCoord){ assert( sizeof(u32)==4 ); #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 i = __builtin_bswap32(pCoord->u); - memcpy(p, &i, 4); + memmove(p, &i, 4); #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 i = _byteswap_ulong(pCoord->u); - memcpy(p, &i, 4); + memmove(p, &i, 4); #elif SQLITE_BYTEORDER==4321 i = pCoord->u; - memcpy(p, &i, 4); + memmove(p, &i, 4); #else i = pCoord->u; p[0] = (i>>24)&0xFF; @@ -167544,12 +167544,12 @@ static int writeCoord(u8 *p, RtreeCoord *pCoord){ static int writeInt64(u8 *p, i64 i){ #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 i = (i64)__builtin_bswap64((u64)i); - memcpy(p, &i, 8); + memmove(p, &i, 8); #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 i = (i64)_byteswap_uint64((u64)i); - memcpy(p, &i, 8); + memmove(p, &i, 8); #elif SQLITE_BYTEORDER==4321 - memcpy(p, &i, 8); + memmove(p, &i, 8); #else p[0] = (i>>56)&0xFF; p[1] = (i>>48)&0xFF; @@ -168107,7 +168107,7 @@ static int rtreeEof(sqlite3_vtab_cursor *cur){ #elif SQLITE_BYTEORDER==1234 #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ - memcpy(&c.u,a,4); \ + memmove(&c.u,a,4); \ c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \ ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ @@ -168115,7 +168115,7 @@ static int rtreeEof(sqlite3_vtab_cursor *cur){ #elif SQLITE_BYTEORDER==4321 #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ - memcpy(&c.u,a,4); \ + memmove(&c.u,a,4); \ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ } #else @@ -168697,7 +168697,7 @@ static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){ if( !pInfo ) return SQLITE_NOMEM; memset(pInfo, 0, sizeof(*pInfo)); pBlob = (RtreeMatchArg*)&pInfo[1]; - memcpy(pBlob, pSrc, pSrc->iSize); + memmove(pBlob, pSrc, pSrc->iSize); pInfo->pContext = pBlob->cb.pContext; pInfo->nParam = pBlob->nParam; pInfo->aParam = pBlob->aParam; @@ -169021,7 +169021,7 @@ static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){ RtreeDValue area; RtreeCell cell; - memcpy(&cell, p, sizeof(RtreeCell)); + memmove(&cell, p, sizeof(RtreeCell)); area = cellArea(pRtree, &cell); cellUnion(pRtree, &cell, pCell); return (cellArea(pRtree, &cell)-area); @@ -169203,7 +169203,7 @@ static void SortByDistance( SortByDistance(aLeft, nLeft, aDistance, aSpare); SortByDistance(aRight, nRight, aDistance, aSpare); - memcpy(aSpare, aLeft, sizeof(int)*nLeft); + memmove(aSpare, aLeft, sizeof(int)*nLeft); aLeft = aSpare; while( iLeftiNode==1 ){ @@ -169753,7 +169753,7 @@ static int Reinsert( for(ii=0; iinDim2 = pRtree->nDim*2; pRtree->nBytesPerCell = 8 + pRtree->nDim2*4; pRtree->eCoordType = (u8)eCoordType; - memcpy(pRtree->zDb, argv[1], nDb); - memcpy(pRtree->zName, argv[2], nName); + memmove(pRtree->zDb, argv[1], nDb); + memmove(pRtree->zName, argv[2], nName); /* Figure out the node size to use. */ rc = getNodeSize(db, pRtree, isCreate, pzErr); @@ -170776,7 +170776,7 @@ static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){ if( pRet==0 ){ pCheck->rc = SQLITE_NOMEM; }else{ - memcpy(pRet, pNode, nNode); + memmove(pRet, pNode, nNode); *pnNode = nNode; } } @@ -171909,7 +171909,7 @@ static int icuCreate( if( n ){ p->zLocale = (char *)&p[1]; - memcpy(p->zLocale, argv[0], n); + memmove(p->zLocale, argv[0], n); } *ppTokenizer = (sqlite3_tokenizer *)p; @@ -173285,7 +173285,7 @@ static int rbuDeltaApply( /* ERROR: copy extends past end of input */ return -1; } - memcpy(zOut, &zSrc[ofst], cnt); + memmove(zOut, &zSrc[ofst], cnt); zOut += cnt; break; } @@ -173300,7 +173300,7 @@ static int rbuDeltaApply( /* ERROR: insert count exceeds size of delta */ return -1; } - memcpy(zOut, zDelta, cnt); + memmove(zOut, zDelta, cnt); zOut += cnt; zDelta += cnt; lenDelta -= cnt; @@ -173790,7 +173790,7 @@ static char *rbuStrndup(const char *zStr, int *pRc){ size_t nCopy = strlen(zStr) + 1; zRet = (char*)sqlite3_malloc64(nCopy); if( zRet ){ - memcpy(zRet, zStr, nCopy); + memmove(zRet, zStr, nCopy); }else{ *pRc = SQLITE_NOMEM; } @@ -173943,7 +173943,7 @@ static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){ int bIndex = 0; if( p->rc==SQLITE_OK ){ - memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol); + memmove(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol); p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) ); @@ -174932,7 +174932,7 @@ static int rbuGetUpdateStmt( char *zUpdate = 0; pUp->zMask = (char*)&pUp[1]; - memcpy(pUp->zMask, zMask, pIter->nTblCol); + memmove(pUp->zMask, zMask, pIter->nTblCol); pUp->pNext = pIter->pRbuUpdate; pIter->pRbuUpdate = pUp; @@ -175085,9 +175085,9 @@ static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){ ** the RBU db handle now. */ if( p->zState ){ rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState); - memcpy(p->zStateDb, "stat", 4); + memmove(p->zStateDb, "stat", 4); }else{ - memcpy(p->zStateDb, "main", 4); + memmove(p->zStateDb, "main", 4); } #if 0 @@ -176275,11 +176275,11 @@ static sqlite3rbu *openRbuHandle( int bRetry = 0; if( zTarget ){ p->zTarget = pCsr; - memcpy(p->zTarget, zTarget, nTarget+1); + memmove(p->zTarget, zTarget, nTarget+1); pCsr += nTarget+1; } p->zRbu = pCsr; - memcpy(p->zRbu, zRbu, nRbu+1); + memmove(p->zRbu, zRbu, nRbu+1); pCsr += nRbu+1; if( zState ){ p->zState = rbuMPrintf(p, "%s", zState); @@ -177283,7 +177283,7 @@ static int rbuVfsOpen( nCopy = strlen(zBase); zCopy = sqlite3_malloc64(nCopy+2); if( zCopy ){ - memcpy(zCopy, zBase, nCopy); + memmove(zCopy, zBase, nCopy); zCopy[nCopy-3] = 'o'; zCopy[nCopy] = '\0'; zCopy[nCopy+1] = '\0'; @@ -177540,12 +177540,12 @@ SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){ rc = SQLITE_NOTFOUND; }else{ char *zSpace; - memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs)); + memmove(&pNew->base, &vfs_template, sizeof(sqlite3_vfs)); pNew->base.mxPathname = pParent->mxPathname; pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile; pNew->pRealVfs = pParent; pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]); - memcpy(zSpace, zName, nName); + memmove(zSpace, zName, nName); /* Allocate the mutex and register the new VFS (not as the default) */ pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE); @@ -178641,7 +178641,7 @@ static int dbpageUpdate( if( rc==SQLITE_OK ){ rc = sqlite3PagerWrite(pDbPage); if( rc==SQLITE_OK ){ - memcpy(sqlite3PagerGetData(pDbPage), + memmove(sqlite3PagerGetData(pDbPage), sqlite3_value_blob(argv[3]), szPage); } @@ -179062,7 +179062,7 @@ static int sessionSerializeValue( double r; assert( sizeof(double)==8 && sizeof(u64)==8 ); r = sqlite3_value_double(pValue); - memcpy(&i, &r, 8); + memmove(&i, &r, 8); } sessionPutI64(&aBuf[1], i); } @@ -179086,7 +179086,7 @@ static int sessionSerializeValue( if( aBuf ){ sessionVarintPut(&aBuf[1], n); - if( n ) memcpy(&aBuf[nVarint + 1], z, n); + if( n ) memmove(&aBuf[nVarint + 1], z, n); } nByte = 1 + nVarint + n; @@ -179192,7 +179192,7 @@ static int sessionPreupdateHash( }else{ double rVal = sqlite3_value_double(pVal); assert( sizeof(iVal)==8 && sizeof(rVal)==8 ); - memcpy(&iVal, &rVal, 8); + memmove(&iVal, &rVal, 8); } h = sessionHashAppendI64(h, iVal); }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ @@ -179348,10 +179348,10 @@ static void sessionMergeRecord( int n1 = sessionSerialLen(a1); int n2 = sessionSerialLen(a2); if( *a2 ){ - memcpy(aOut, a2, n2); + memmove(aOut, a2, n2); aOut += n2; }else{ - memcpy(aOut, a1, n1); + memmove(aOut, a1, n1); aOut += n1; } a1 += n1; @@ -179446,7 +179446,7 @@ static int sessionMergeUpdate( aNew = sessionMergeValue(&aNew1, &aNew2, &nNew); if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){ if( pTab->abPK[i]==0 ) bRequired = 1; - memcpy(aOut, aOld, nOld); + memmove(aOut, aOld, nOld); aOut += nOld; }else{ *(aOut++) = '\0'; @@ -179474,7 +179474,7 @@ static int sessionMergeUpdate( ){ *(aOut++) = '\0'; }else{ - memcpy(aOut, aNew, nNew); + memmove(aOut, aNew, nNew); aOut += nNew; } } @@ -179536,7 +179536,7 @@ static int sessionPreupdateEqual( }else{ double rVal; assert( sizeof(iVal)==8 && sizeof(rVal)==8 ); - memcpy(&rVal, &iVal, 8); + memmove(&rVal, &iVal, 8); if( sqlite3_value_double(pVal)!=rVal ) return 0; } }else{ @@ -179695,7 +179695,7 @@ static int sessionTableInfo( abPK = (u8 *)pAlloc; pAlloc = &abPK[nDbCol]; if( pzTab ){ - memcpy(pAlloc, zThis, nThis+1); + memmove(pAlloc, zThis, nThis+1); *pzTab = (char *)pAlloc; pAlloc += nThis+1; } @@ -179705,7 +179705,7 @@ static int sessionTableInfo( int nName = sqlite3_column_bytes(pStmt, 1); const unsigned char *zName = sqlite3_column_text(pStmt, 1); if( zName==0 ) break; - memcpy(pAlloc, zName, nName+1); + memmove(pAlloc, zName, nName+1); azCol[i] = (char *)pAlloc; pAlloc += nName+1; abPK[i] = sqlite3_column_int(pStmt, 5); @@ -180357,7 +180357,7 @@ SQLITE_API int sqlite3session_create( pNew->db = db; pNew->zDb = (char *)&pNew[1]; pNew->bEnable = 1; - memcpy(pNew->zDb, zDb, nDb+1); + memmove(pNew->zDb, zDb, nDb+1); sessionPreupdateHooks(pNew); /* Add the new session object to the linked list of session objects @@ -180482,7 +180482,7 @@ SQLITE_API int sqlite3session_attach( SessionTable **ppTab; memset(pTab, 0, sizeof(SessionTable)); pTab->zName = (char *)&pTab[1]; - memcpy(pTab->zName, zName, nName+1); + memmove(pTab->zName, zName, nName+1); for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext); *ppTab = pTab; } @@ -180582,7 +180582,7 @@ static void sessionAppendBlob( int *pRc ){ if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){ - memcpy(&p->aBuf[p->nBuf], aBlob, nBlob); + memmove(&p->aBuf[p->nBuf], aBlob, nBlob); p->nBuf += nBlob; } } @@ -180602,7 +180602,7 @@ static void sessionAppendStr( ){ int nStr = sqlite3Strlen30(zStr); if( 0==sessionBufferGrow(p, nStr, pRc) ){ - memcpy(&p->aBuf[p->nBuf], zStr, nStr); + memmove(&p->aBuf[p->nBuf], zStr, nStr); p->nBuf += nStr; } } @@ -180675,7 +180675,7 @@ static void sessionAppendCol( i = sqlite3_column_int64(pStmt, iCol); }else{ double r = sqlite3_column_double(pStmt, iCol); - memcpy(&i, &r, 8); + memmove(&i, &r, 8); } sessionPutI64(aBuf, i); sessionAppendBlob(p, aBuf, 8, pRc); @@ -180758,7 +180758,7 @@ static int sessionAppendUpdate( if( iVal==sqlite3_column_int64(pStmt, i) ) break; }else{ double dVal; - memcpy(&dVal, &iVal, 8); + memmove(&dVal, &iVal, 8); if( dVal==sqlite3_column_double(pStmt, i) ) break; } } @@ -180963,7 +180963,7 @@ static int sessionSelectBind( if( abPK[i] ){ double rVal; i64 iVal = sessionGetI64(a); - memcpy(&rVal, &iVal, 8); + memmove(&rVal, &iVal, 8); rc = sqlite3_bind_double(pSelect, i+1, rVal); } a += 8; @@ -181387,7 +181387,7 @@ static int sessionValueSetStr( ** error. Hence the code to create the copy externally. */ u8 *aCopy = sqlite3_malloc(nData+1); if( aCopy==0 ) return SQLITE_NOMEM; - memcpy(aCopy, aData, nData); + memmove(aCopy, aData, nData); sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free); return SQLITE_OK; } @@ -181457,7 +181457,7 @@ static int sessionReadRecord( sqlite3VdbeMemSetInt64(apOut[i], v); }else{ double d; - memcpy(&d, &v, 8); + memmove(&d, &v, 8); sqlite3VdbeMemSetDouble(apOut[i], d); } pIn->iNext += 8; @@ -181577,7 +181577,7 @@ static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){ if( rc==SQLITE_OK ){ int iPK = sizeof(sqlite3_value*)*p->nCol*2; memset(p->tblhdr.aBuf, 0, iPK); - memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy); + memmove(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy); p->in.iNext += nCopy; } @@ -183105,7 +183105,7 @@ static int sessionChangeMerge( pNew->bIndirect = bIndirect; pNew->nRecord = nRec; pNew->aRecord = (u8*)&pNew[1]; - memcpy(pNew->aRecord, aRec, nRec); + memmove(pNew->aRecord, aRec, nRec); }else{ int op1 = pExist->op; @@ -183159,7 +183159,7 @@ static int sessionChangeMerge( assert( op2==SQLITE_INSERT ); pNew->op = SQLITE_UPDATE; if( bPatchset ){ - memcpy(aCsr, aRec, nRec); + memmove(aCsr, aRec, nRec); aCsr += nRec; }else{ if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){ @@ -183184,7 +183184,7 @@ static int sessionChangeMerge( assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE ); pNew->op = SQLITE_DELETE; if( bPatchset ){ - memcpy(aCsr, aRec, nRec); + memmove(aCsr, aRec, nRec); aCsr += nRec; }else{ sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist); @@ -183254,9 +183254,9 @@ static int sessionChangesetToHash( memset(pTab, 0, sizeof(SessionTable)); pTab->nCol = nCol; pTab->abPK = (u8*)&pTab[1]; - memcpy(pTab->abPK, abPK, nCol); + memmove(pTab->abPK, abPK, nCol); pTab->zName = (char*)&pTab->abPK[nCol]; - memcpy(pTab->zName, zNew, nNew+1); + memmove(pTab->zName, zNew, nNew+1); /* The new object must be linked on to the end of the list, not ** simply added to the start of it. This is to ensure that the @@ -183761,7 +183761,7 @@ static int jsonGrow(JsonString *p, u32 N){ jsonOom(p); return SQLITE_NOMEM; } - memcpy(zNew, p->zBuf, (size_t)p->nUsed); + memmove(zNew, p->zBuf, (size_t)p->nUsed); p->zBuf = zNew; p->bStatic = 0; }else{ @@ -183780,7 +183780,7 @@ static int jsonGrow(JsonString *p, u32 N){ */ static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){ if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return; - memcpy(p->zBuf+p->nUsed, zIn, N); + memmove(p->zBuf+p->nUsed, zIn, N); p->nUsed += N; } @@ -184532,7 +184532,7 @@ static JsonParse *jsonParseCached( } memset(p, 0, sizeof(*p)); p->zJson = (char*)&p[1]; - memcpy((char*)p->zJson, zJson, nJson+1); + memmove((char*)p->zJson, zJson, nJson+1); if( jsonParse(p, pCtx, p->zJson) ){ sqlite3_free(p); return 0; @@ -185747,7 +185747,7 @@ static int jsonEachFilter( n = sqlite3_value_bytes(argv[0]); p->zJson = sqlite3_malloc64( n+1 ); if( p->zJson==0 ) return SQLITE_NOMEM; - memcpy(p->zJson, z, (size_t)n+1); + memmove(p->zJson, z, (size_t)n+1); if( jsonParse(&p->sParse, 0, p->zJson) ){ int rc = SQLITE_NOMEM; if( p->sParse.oom==0 ){ @@ -185769,7 +185769,7 @@ static int jsonEachFilter( n = sqlite3_value_bytes(argv[1]); p->zRoot = sqlite3_malloc64( n+1 ); if( p->zRoot==0 ) return SQLITE_NOMEM; - memcpy(p->zRoot, zRoot, (size_t)n+1); + memmove(p->zRoot, zRoot, (size_t)n+1); if( zRoot[0]!='$' ){ zErr = zRoot; }else{ @@ -189533,7 +189533,7 @@ static void sqlite3Fts5BufferAppendBlob( assert_nc( *pRc || nData>=0 ); if( nData ){ if( fts5BufferGrow(pRc, pBuf, nData) ) return; - memcpy(&pBuf->p[pBuf->n], pData, nData); + memmove(&pBuf->p[pBuf->n], pData, nData); pBuf->n += nData; } } @@ -189737,7 +189737,7 @@ static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){ } zRet = (char*)sqlite3_malloc(nIn+1); if( zRet ){ - memcpy(zRet, pIn, nIn); + memmove(zRet, pIn, nIn); zRet[nIn] = '\0'; }else{ *pRc = SQLITE_NOMEM; @@ -189832,7 +189832,7 @@ static int sqlite3Fts5TermsetAdd( pEntry->pTerm = (char*)&pEntry[1]; pEntry->nTerm = nTerm; pEntry->iIdx = iIdx; - memcpy(pEntry->pTerm, pTerm, nTerm); + memmove(pEntry->pTerm, pTerm, nTerm); pEntry->pNext = p->apHash[hash]; p->apHash[hash] = pEntry; } @@ -190172,7 +190172,7 @@ static int fts5ConfigParseSpecial( p = fts5ConfigSkipBareword(p2); } if( p ){ - memcpy(pSpace, p2, p-p2); + memmove(pSpace, p2, p-p2); azArg[nArg] = pSpace; sqlite3Fts5Dequote(pSpace); pSpace += (p - p2) + 1; @@ -190294,7 +190294,7 @@ static const char *fts5ConfigGobbleWord( if( zOut==0 ){ *pRc = SQLITE_NOMEM; }else{ - memcpy(zOut, zIn, nIn+1); + memmove(zOut, zIn, nIn+1); if( fts5_isopenquote(zOut[0]) ){ int ii = fts5Dequote(zOut); zRet = &zIn[ii]; @@ -190638,7 +190638,7 @@ static int sqlite3Fts5ConfigParseRank( if( p ){ zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank); - if( zRank ) memcpy(zRank, pRank, p-pRank); + if( zRank ) memmove(zRank, pRank, p-pRank); }else{ rc = SQLITE_ERROR; } @@ -190658,7 +190658,7 @@ static int sqlite3Fts5ConfigParseRank( rc = SQLITE_ERROR; }else{ zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs); - if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs); + if( zRankArgs ) memmove(zRankArgs, pArgs, p-pArgs); } } } @@ -191182,7 +191182,7 @@ static int fts5ExprSynonymList( rc = SQLITE_NOMEM; goto synonym_poslist_out; } - memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter); + memmove(aNew, aIter, sizeof(Fts5PoslistReader) * nIter); nAlloc = nAlloc*2; if( aIter!=aStatic ) sqlite3_free(aIter); aIter = aNew; @@ -192383,7 +192383,7 @@ static int fts5ParseTokenize( }else{ memset(pSyn, 0, nByte); pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer); - memcpy(pSyn->zTerm, pToken, nToken); + memmove(pSyn->zTerm, pToken, nToken); pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym; pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn; } @@ -192539,7 +192539,7 @@ static int sqlite3Fts5ExprClonePhrase( int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int); Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte); if( pColset ){ - memcpy(pColset, pColsetOrig, nByte); + memmove(pColset, pColsetOrig, nByte); } pNew->pRoot->pNear->pColset = pColset; } @@ -192756,7 +192756,7 @@ static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){ int nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int); pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte); if( pRet ){ - memcpy(pRet, pOrig, nByte); + memmove(pRet, pOrig, nByte); } }else{ pRet = 0; @@ -192884,7 +192884,7 @@ static void fts5ExprAssignXNext(Fts5ExprNode *pNode){ static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){ if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){ int nByte = sizeof(Fts5ExprNode*) * pSub->nChild; - memcpy(&p->apChild[p->nChild], pSub->apChild, nByte); + memmove(&p->apChild[p->nChild], pSub->apChild, nByte); p->nChild += pSub->nChild; sqlite3_free(pSub); }else{ @@ -193940,7 +193940,7 @@ static int sqlite3Fts5HashWrite( p->nAlloc = nByte; zKey = fts5EntryKey(p); zKey[0] = bByte; - memcpy(&zKey[1], pToken, nToken); + memmove(&zKey[1], pToken, nToken); assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) ); p->nKey = nToken; zKey[nToken+1] = '\0'; @@ -195298,7 +195298,7 @@ static int fts5StructureCountSegments(Fts5Structure *pStruct){ #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \ assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \ - memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \ + memmove(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \ (pBuf)->n += nBlob; \ } @@ -195396,7 +195396,7 @@ static void fts5StructurePromoteTo( if( sz>szPromote ) return; fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1); if( p->rc ) return; - memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment)); + memmove(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment)); pOut->nSeg++; pLvl->nSeg--; } @@ -199304,7 +199304,7 @@ static void fts5SetupPrefixIter( if( pData ){ pData->p = (u8*)&pData[1]; pData->nn = pData->szLeaf = doclist.n; - if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n); + if( doclist.n ) memmove(pData->p, doclist.p, doclist.n); fts5MultiIterNew2(p, pData, bDesc, ppIter); } fts5BufferFree(&doclist); @@ -199543,7 +199543,7 @@ static int sqlite3Fts5IndexQuery( if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){ int iIdx = 0; /* Index to search */ - if( nToken ) memcpy(&buf.p[1], pToken, nToken); + if( nToken ) memmove(&buf.p[1], pToken, nToken); /* Figure out which index to search and set iIdx accordingly. If this ** is a prefix query for which there is no prefix index, set iIdx to @@ -200474,7 +200474,7 @@ static void fts5DecodeFunction( nSpace = n + FTS5_DATA_ZERO_PADDING; a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace); if( a==0 ) goto decode_out; - memcpy(a, aBlob, n); + memmove(a, aBlob, n); fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno); @@ -203162,7 +203162,7 @@ static int fts5CreateAux( if( pAux ){ memset(pAux, 0, nByte); pAux->zFunc = (char*)&pAux[1]; - memcpy(pAux->zFunc, zName, nName); + memmove(pAux->zFunc, zName, nName); pAux->pGlobal = pGlobal; pAux->pUserData = pUserData; pAux->xFunc = xFunc; @@ -203200,7 +203200,7 @@ static int fts5CreateTokenizer( if( pNew ){ memset(pNew, 0, nByte); pNew->zName = (char*)&pNew[1]; - memcpy(pNew->zName, zName, nName); + memmove(pNew->zName, zName, nName); pNew->pUserData = pUserData; pNew->x = *pTokenizer; pNew->xDestroy = xDestroy; @@ -204660,7 +204660,7 @@ static int fts5AsciiCreate( }else{ int i; memset(p, 0, sizeof(AsciiTokenizer)); - memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar)); + memmove(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar)); for(i=0; rc==SQLITE_OK && iaTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar)); + memmove(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar)); p->bRemoveDiacritic = 1; p->nFold = 64; p->aFold = sqlite3_malloc(p->nFold * sizeof(char)); @@ -205032,7 +205032,7 @@ static int fts5UnicodeTokenize( goto tokenize_done; } zOut = &aFold[zOut - p->aFold]; - memcpy(aFold, p->aFold, nFold); + memmove(aFold, p->aFold, nFold); sqlite3_free(p->aFold); p->aFold = aFold; p->nFold = nFold = nFold*2; @@ -205173,7 +205173,7 @@ static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){ if( p->zSuffix ){ int nStem = nBuf - p->nSuffix; if( p->xCond==0 || p->xCond(aBuf, nStem) ){ - memcpy(&aBuf[nStem], p->zOutput, p->nOutput); + memmove(&aBuf[nStem], p->zOutput, p->nOutput); *pnBuf = nStem + p->nOutput; ret = p - aRule; } @@ -205412,7 +205412,7 @@ static int fts5PorterStep1B2(char *aBuf, int *pnBuf){ case 'a': if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){ - memcpy(&aBuf[nBuf-2], "ate", 3); + memmove(&aBuf[nBuf-2], "ate", 3); *pnBuf = nBuf - 2 + 3; ret = 1; } @@ -205420,7 +205420,7 @@ static int fts5PorterStep1B2(char *aBuf, int *pnBuf){ case 'b': if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){ - memcpy(&aBuf[nBuf-2], "ble", 3); + memmove(&aBuf[nBuf-2], "ble", 3); *pnBuf = nBuf - 2 + 3; ret = 1; } @@ -205428,7 +205428,7 @@ static int fts5PorterStep1B2(char *aBuf, int *pnBuf){ case 'i': if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){ - memcpy(&aBuf[nBuf-2], "ize", 3); + memmove(&aBuf[nBuf-2], "ize", 3); *pnBuf = nBuf - 2 + 3; ret = 1; } @@ -205447,12 +205447,12 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){ case 'a': if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){ if( fts5Porter_MGt0(aBuf, nBuf-7) ){ - memcpy(&aBuf[nBuf-7], "ate", 3); + memmove(&aBuf[nBuf-7], "ate", 3); *pnBuf = nBuf - 7 + 3; } }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){ if( fts5Porter_MGt0(aBuf, nBuf-6) ){ - memcpy(&aBuf[nBuf-6], "tion", 4); + memmove(&aBuf[nBuf-6], "tion", 4); *pnBuf = nBuf - 6 + 4; } } @@ -205461,12 +205461,12 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){ case 'c': if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ - memcpy(&aBuf[nBuf-4], "ence", 4); + memmove(&aBuf[nBuf-4], "ence", 4); *pnBuf = nBuf - 4 + 4; } }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ - memcpy(&aBuf[nBuf-4], "ance", 4); + memmove(&aBuf[nBuf-4], "ance", 4); *pnBuf = nBuf - 4 + 4; } } @@ -205475,7 +205475,7 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){ case 'e': if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ - memcpy(&aBuf[nBuf-4], "ize", 3); + memmove(&aBuf[nBuf-4], "ize", 3); *pnBuf = nBuf - 4 + 3; } } @@ -205484,7 +205484,7 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){ case 'g': if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ - memcpy(&aBuf[nBuf-4], "log", 3); + memmove(&aBuf[nBuf-4], "log", 3); *pnBuf = nBuf - 4 + 3; } } @@ -205493,27 +205493,27 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){ case 'l': if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt0(aBuf, nBuf-3) ){ - memcpy(&aBuf[nBuf-3], "ble", 3); + memmove(&aBuf[nBuf-3], "ble", 3); *pnBuf = nBuf - 3 + 3; } }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ - memcpy(&aBuf[nBuf-4], "al", 2); + memmove(&aBuf[nBuf-4], "al", 2); *pnBuf = nBuf - 4 + 2; } }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ - memcpy(&aBuf[nBuf-5], "ent", 3); + memmove(&aBuf[nBuf-5], "ent", 3); *pnBuf = nBuf - 5 + 3; } }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt0(aBuf, nBuf-3) ){ - memcpy(&aBuf[nBuf-3], "e", 1); + memmove(&aBuf[nBuf-3], "e", 1); *pnBuf = nBuf - 3 + 1; } }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ - memcpy(&aBuf[nBuf-5], "ous", 3); + memmove(&aBuf[nBuf-5], "ous", 3); *pnBuf = nBuf - 5 + 3; } } @@ -205522,17 +205522,17 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){ case 'o': if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){ if( fts5Porter_MGt0(aBuf, nBuf-7) ){ - memcpy(&aBuf[nBuf-7], "ize", 3); + memmove(&aBuf[nBuf-7], "ize", 3); *pnBuf = nBuf - 7 + 3; } }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ - memcpy(&aBuf[nBuf-5], "ate", 3); + memmove(&aBuf[nBuf-5], "ate", 3); *pnBuf = nBuf - 5 + 3; } }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ - memcpy(&aBuf[nBuf-4], "ate", 3); + memmove(&aBuf[nBuf-4], "ate", 3); *pnBuf = nBuf - 4 + 3; } } @@ -205541,22 +205541,22 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){ case 's': if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ - memcpy(&aBuf[nBuf-5], "al", 2); + memmove(&aBuf[nBuf-5], "al", 2); *pnBuf = nBuf - 5 + 2; } }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){ if( fts5Porter_MGt0(aBuf, nBuf-7) ){ - memcpy(&aBuf[nBuf-7], "ive", 3); + memmove(&aBuf[nBuf-7], "ive", 3); *pnBuf = nBuf - 7 + 3; } }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){ if( fts5Porter_MGt0(aBuf, nBuf-7) ){ - memcpy(&aBuf[nBuf-7], "ful", 3); + memmove(&aBuf[nBuf-7], "ful", 3); *pnBuf = nBuf - 7 + 3; } }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){ if( fts5Porter_MGt0(aBuf, nBuf-7) ){ - memcpy(&aBuf[nBuf-7], "ous", 3); + memmove(&aBuf[nBuf-7], "ous", 3); *pnBuf = nBuf - 7 + 3; } } @@ -205565,17 +205565,17 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){ case 't': if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ - memcpy(&aBuf[nBuf-5], "al", 2); + memmove(&aBuf[nBuf-5], "al", 2); *pnBuf = nBuf - 5 + 2; } }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ - memcpy(&aBuf[nBuf-5], "ive", 3); + memmove(&aBuf[nBuf-5], "ive", 3); *pnBuf = nBuf - 5 + 3; } }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){ if( fts5Porter_MGt0(aBuf, nBuf-6) ){ - memcpy(&aBuf[nBuf-6], "ble", 3); + memmove(&aBuf[nBuf-6], "ble", 3); *pnBuf = nBuf - 6 + 3; } } @@ -205594,7 +205594,7 @@ static int fts5PorterStep3(char *aBuf, int *pnBuf){ case 'a': if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ - memcpy(&aBuf[nBuf-4], "ic", 2); + memmove(&aBuf[nBuf-4], "ic", 2); *pnBuf = nBuf - 4 + 2; } } @@ -205611,12 +205611,12 @@ static int fts5PorterStep3(char *aBuf, int *pnBuf){ case 't': if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ - memcpy(&aBuf[nBuf-5], "ic", 2); + memmove(&aBuf[nBuf-5], "ic", 2); *pnBuf = nBuf - 5 + 2; } }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ - memcpy(&aBuf[nBuf-5], "ic", 2); + memmove(&aBuf[nBuf-5], "ic", 2); *pnBuf = nBuf - 5 + 2; } } @@ -205641,7 +205641,7 @@ static int fts5PorterStep3(char *aBuf, int *pnBuf){ case 'z': if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ - memcpy(&aBuf[nBuf-5], "al", 2); + memmove(&aBuf[nBuf-5], "al", 2); *pnBuf = nBuf - 5 + 2; } } @@ -205660,7 +205660,7 @@ static int fts5PorterStep1B(char *aBuf, int *pnBuf){ case 'e': if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt0(aBuf, nBuf-3) ){ - memcpy(&aBuf[nBuf-3], "ee", 2); + memmove(&aBuf[nBuf-3], "ee", 2); *pnBuf = nBuf - 3 + 2; } }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){ @@ -205723,7 +205723,7 @@ static int fts5PorterCb( if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through; aBuf = p->aBuf; nBuf = nToken; - memcpy(aBuf, pToken, nBuf); + memmove(aBuf, pToken, nBuf); /* Step 1. */ fts5PorterStep1A(aBuf, &nBuf); @@ -206743,8 +206743,8 @@ static int fts5VocabInitVtab( pRet->db = db; pRet->zFts5Tbl = (char*)&pRet[1]; pRet->zFts5Db = &pRet->zFts5Tbl[nTab]; - memcpy(pRet->zFts5Tbl, zTab, nTab); - memcpy(pRet->zFts5Db, zDb, nDb); + memmove(pRet->zFts5Tbl, zTab, nTab); + memmove(pRet->zFts5Db, zDb, nDb); sqlite3Fts5Dequote(pRet->zFts5Tbl); sqlite3Fts5Dequote(pRet->zFts5Db); } @@ -207151,7 +207151,7 @@ static int fts5VocabFilterMethod( if( pCsr->zLeTerm==0 ){ rc = SQLITE_NOMEM; }else{ - memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1); + memmove(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1); } } } diff --git a/packages/prism/src/c/mp/mp_sw.c b/packages/prism/src/c/mp/mp_sw.c index dad3c3a01..5b48a1e8c 100644 --- a/packages/prism/src/c/mp/mp_sw.c +++ b/packages/prism/src/c/mp/mp_sw.c @@ -186,7 +186,7 @@ int pc_mpm_alloc_occ_switches_0(void) occ_switches = MALLOC(sizeof(SW_INS_PTR) * sw_tab_size); occ_switch_tab_size = sw_tab_size; - memcpy(occ_switches, switches, sizeof(SW_INS_PTR) * sw_tab_size); + memmove(occ_switches, switches, sizeof(SW_INS_PTR) * sw_tab_size); if (fix_init_order) { sort_occ_switches(); } diff --git a/packages/python/CMakeLists.txt b/packages/python/CMakeLists.txt index 17787b257..1314dca1e 100644 --- a/packages/python/CMakeLists.txt +++ b/packages/python/CMakeLists.txt @@ -5,7 +5,7 @@ set (PYTHON_SOURCES python.c pl2py.c pybips.c py2pl.c pl2pl.c pypreds.c pyio.c) set (PYTHON_HEADERS py4yap.h) set (CMAKE_POSITION_INDEPENDENT_CODE TRUE) -include_directories( ${CMAKE_BINARY_DIR} ${PYTHON_INCLUDE_DIRS} +include_directories( BEFORE ${PYTHON_INCLUDE_DIRS} ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/os ) #talk to python.pl diff --git a/packages/python/pl2py.c b/packages/python/pl2py.c index 65e12dacf..167df5679 100644 --- a/packages/python/pl2py.c +++ b/packages/python/pl2py.c @@ -112,7 +112,7 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) { // Yap_DebugPlWriteln(yt); switch (PL_term_type(t)) { case PL_VARIABLE: { - if (t == 0) { + if (yt == 0) { Yap_ThrowError(SYSTEM_ERROR_INTERNAL, yt, "in term_to_python"); } PyObject *out = PyTuple_New(1); @@ -148,21 +148,20 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) { } else if (YAP_IsStringTerm(yt)) { s = YAP_StringOfTerm(yt); } else { - return CHECKNULL(t, NULL); + return CHECKNULL(t, NULL); } + PyObject *pobj = PyUnicode_FromString(s); + #if PY_MAJOR_VERSION < 3 if (proper_ascii_string(s)) { PyObject *o = PyString_FromStringAndSize(s, strlen(s)); return CHECKNULL(t, o); - } else + } #endif - { // char *p = malloc(strlen(s)+1); // strcpy(p, s); - PyObject *pobj = PyUnicode_FromString(s); Py_IncRef(pobj); return CHECKNULL(t, pobj); - } } break; case PL_INTEGER: { int64_t j; @@ -406,8 +405,8 @@ PyObject *deref_term_to_python(term_t t) { // am\n"); YAP_Term yt = YAP_GetFromSlot(t); if (YAP_IsVarTerm(yt)) { - char s[32]; - char *o = YAP_WriteBuffer(yt, s, 31, 0); + char b[1024]; + char *o = YAP_WriteBuffer(yt, b, 1023, 0); PyObject *p = PyUnicode_FromString(o); return p; } diff --git a/packages/python/py2pl.c b/packages/python/py2pl.c index 889c40c08..d6606001f 100644 --- a/packages/python/py2pl.c +++ b/packages/python/py2pl.c @@ -46,11 +46,12 @@ foreign_t assign_to_symbol(term_t t, PyObject *e) { PyObject *dic; if (!lookupPySymbol(s, NULL, &dic)) dic = py_Main; - Py_INCREF(e); + Py_INCREF(e); return PyObject_SetAttrString(dic, s, e) == 0; } -foreign_t python_to_term(PyObject *pVal, term_t t) { +foreign_t python_to_term(PyObject *pVal, term_t t) +{ bool rc = true; term_t to = PL_new_term_ref(); // fputs(" <<*** ",stderr); PyObject_Print(pVal,stderr,0); @@ -89,14 +90,14 @@ foreign_t python_to_term(PyObject *pVal, term_t t) { #else const char *s = PyUnicode_AsUTF8(pVal); #endif -// if (PyDict_GetItemString(py_Atoms, s)) -// rc = rc && PL_unify_atom_chars(t, s); -// else + if (Yap_AtomInUse(s)) rc = rc && PL_unify_atom_chars(t, s); - } else if (PyByteArray_Check(pVal)) { - rc = rc && PL_unify_string_chars(t, PyByteArray_AsString(pVal)); - #if PY_MAJOR_VERSION < 3 - } else if (PyString_Check(pVal)) { + else + rc = rc && PL_unify_string_chars(t, s); + } else if (PyByteArray_Check(pVal)) { + rc = rc && PL_unify_string_chars(t, PyByteArray_AsString(pVal)); +#if PY_MAJOR_VERSION < 3 + } else if (PyString_Check(pVal)) { rc = rc && PL_unify_string_chars(t, PyString_AsString(pVal)); #endif } else if (PyTuple_Check(pVal)) { @@ -130,15 +131,18 @@ foreign_t python_to_term(PyObject *pVal, term_t t) { } if (PL_unify_functor(t, f)) { for (i = 0; i < sz; i++) { - if (!PL_get_arg(i + 1, t, to)) + term_t to = PL_new_term_ref(); + if (!PL_get_arg(i + 1, t, to)) rc = false; PyObject *p = PyTuple_GetItem(pVal, i); if (p == NULL) { PyErr_Clear(); p = Py_None; - } - rc = rc && python_to_term(p, to); - } + } else { + rc = rc && python_to_term(p, to); + } + PL_reset_term_refs(to); + } } else { rc = false; } @@ -150,11 +154,13 @@ foreign_t python_to_term(PyObject *pVal, term_t t) { for (i = 0; i < sz; i++) { PyObject *obj; + term_t to = PL_new_term_ref(); rc = rc && PL_unify_list(t, to, t); if ((obj = PyList_GetItem(pVal, i)) == NULL) { obj = Py_None; } rc = rc && python_to_term(obj, to); + PL_reset_term_refs(to); if (!rc) return false; } @@ -163,7 +169,6 @@ foreign_t python_to_term(PyObject *pVal, term_t t) { // Yap_DebugPlWrite(yt); fputs("[***]\n", stderr); } else if (PyDict_Check(pVal)) { Py_ssize_t pos = 0; - term_t to = PL_new_term_ref(), ti = to; int left = PyDict_Size(pVal); PyObject *key, *value; @@ -173,6 +178,7 @@ foreign_t python_to_term(PyObject *pVal, term_t t) { while (PyDict_Next(pVal, &pos, &key, &value)) { term_t tkey = PL_new_term_ref(), tval = PL_new_term_ref(), tint, tnew = PL_new_term_ref(); + term_t to = PL_new_term_ref(); /* do something interesting with the values... */ if (!python_to_term(key, tkey)) { continue; @@ -191,21 +197,22 @@ foreign_t python_to_term(PyObject *pVal, term_t t) { PL_reset_term_refs(tkey); rc = false; } - if (!PL_unify(ti, tint)) { + if (!PL_unify(to, tint)) { rc = false; } - ti = tnew; - PL_reset_term_refs(tkey); } rc = rc && PL_unify(t, to); } } else { rc = rc && repr_term(pVal, t); } - PL_reset_term_refs(to); + return rc; } + + + X_API YAP_Term pythonToYAP(PyObject *pVal) { term_t t = PL_new_term_ref(); @@ -215,12 +222,13 @@ X_API YAP_Term pythonToYAP(PyObject *pVal) { } YAP_Term tt = YAP_GetFromSlot(t); PL_reset_term_refs(t); - //Py_DECREF(pVal); + // Py_DECREF(pVal); return tt; } PyObject *py_Local, *py_Global; + /** * assigns the Python RHS to a Prolog term LHS, ie LHS = RHS * @@ -317,7 +325,7 @@ bool python_assign(term_t t, PyObject *exp, PyObject *context) { if (PySequence_Check(o) && PyInt_Check(i)) { long int j; j = PyInt_AsLong(i); - return PySequence_SetItem(o, i, exp) == 0; + return PySequence_SetItem(o, i, exp) == 0; } #endif if (PyDict_Check(o)) { diff --git a/packages/python/pybips.c b/packages/python/pybips.c index 8874f731e..ecf7ba072 100644 --- a/packages/python/pybips.c +++ b/packages/python/pybips.c @@ -953,10 +953,12 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) { if (!PL_get_arg(1, t, targ)) return NULL; + // Yap_DebugPlWriteln(YAP_GetFromSlot(t)); lhs = term_to_python(targ, true, NULL, true); AOK(PL_get_arg(2, t, targ), NULL); rhs = term_to_python(targ, true, NULL, true); - if (PySequence_Check(lhs) && PySequence_Check(rhs)) { + Yap_DebugPlWriteln(YAP_GetFromSlot(targ)); + if (PySequence_Check(lhs) && PySequence_Check(rhs)) { return PySequence_Concat(lhs, rhs); } if (!PyNumber_Check(lhs)) @@ -1034,11 +1036,11 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) { PyDict_SetItem(pyDict, key, val); } else { indict = false; - pArgs = PyTuple_New(i); + pArgs = PyTuple_New(i); } } - DebugPrintf("Tuple %p\n", pyDict); - if (!indict) { + fprintf(stderr,"Tuple %p: %s\n", pyDict, PyUnicode_AsUTF8(PyObject_Str(pyDict))); + if (!indict) { if (PL_is_variable(tleft)) { pArg = Py_None; } else { diff --git a/packages/python/pyio.c b/packages/python/pyio.c index d748fac32..2eeb9ebd9 100644 --- a/packages/python/pyio.c +++ b/packages/python/pyio.c @@ -146,7 +146,7 @@ static bool getLine(StreamDesc *rl_iostream, int sno) { size_t size = strlen (myrl_line)+1; rl_iostream->u.irl.ptr = rl_iostream->u.irl.buf = (const unsigned char *)malloc(size); - memcpy((void *)rl_iostream->u.irl.buf, myrl_line, size); + memmove((void *)rl_iostream->u.irl.buf, myrl_line, size); return true; } diff --git a/packages/python/pypreds.c b/packages/python/pypreds.c index f7be0bb09..835835f64 100644 --- a/packages/python/pypreds.c +++ b/packages/python/pypreds.c @@ -5,9 +5,12 @@ PyObject *py_Main; void pyErrorHandler__(int line, const char *file, const char *code) { // this code is called if a Python error is found. - fprintf(stderr, " Python error detcted at %s %s:%d\n\n", code, file, line); - PyErr_Print(); -} + //int lvl = push_text_stack(); + PyObject *type, *val; + // PyErr_Fetch(&type, &val, NULL); + // PyErr_Print(); + // Yap_ThrowError__(file,code,line,0, SYSTEM_ERROR_RUNTIME_PYTHON ,"Python Error %s: %s",PyUnicode_AsUTF8(PyObject_Str(type)), PyUnicode_AsUTF8(PyObject_Str(val))); + }; static foreign_t python_len(term_t tobj, term_t tf) { Py_ssize_t len; diff --git a/packages/python/swig/yap4py/yapi.py b/packages/python/swig/yap4py/yapi.py index 06aff6c4c..5f135e122 100644 --- a/packages/python/swig/yap4py/yapi.py +++ b/packages/python/swig/yap4py/yapi.py @@ -41,6 +41,18 @@ class Engine( YAPEngine ): self.goal(release) +class JupyterEngine( Engine ): + + def __init__(self, args=None,self_contained=False,**kwargs): + # type: (object) -> object + if not args: + args = EngineArgs(**kwargs) + args.jupyter = True + Engine.__init__(self, args) + self.goal(set_prolog_flag('verbose', 'silent'),True) + self.goal(compile(library('jupyter')), True) + self.goal(set_prolog_flag('verbose', 'normal'), True) + class EngineArgs( YAPEngineArgs ): """ Interface to Engine Options class""" def __init__(self, args=None,**kwargs): diff --git a/packages/python/yap_kernel/CMakeLists.txt b/packages/python/yap_kernel/CMakeLists.txt index 02422978c..91420dd99 100644 --- a/packages/python/yap_kernel/CMakeLists.txt +++ b/packages/python/yap_kernel/CMakeLists.txt @@ -273,14 +273,15 @@ set (RESOURCES #yap_kernel/resources/logo-32x32.png #yap_kernel/resourcess/logo-64x64.png ) - -set (RENAMED_RESOURCES + +set (RENAMED_RESOURCES yap_kernel/resources/logo-32x32.png yap_kernel/resources/logo-64x64.png # yap_kernel/resources/codemirror/mode/prolog/prolog.js ) set (PL_SOURCES yap_ipython/prolog/jupyter.yap yap_ipython/prolog/complete.yap + yap_ipython/prolog/verify.yap ) set(FILES ${PYTHON_SOURCES} ${PL_SOURCES} ${EXTRAS} ${RESOURCES}) @@ -321,11 +322,13 @@ add_custom_target(YAP_KERNEL ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-64x64.png yap.tgz ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/kernel.js ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/prolog.js ${CMAKE_CURRENT_BINARY_DIR}/yap.tgz ) - + install(CODE "execute_process( COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} build sdist bdist COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PYTHON_USER_INSTALL} --ignore-installed --no-deps . COMMAND ${PYTHON_EXECUTABLE} -m yap_kernel.kernelspec + ERROR_VARIABLE setupErr + OUTPUT_VARIABLE setupOut WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})") install(FILES ${PL_SOURCES} DESTINATION ${libpl} ) diff --git a/packages/python/yap_kernel/yap_ipython/prolog/jupyter.yap b/packages/python/yap_kernel/yap_ipython/prolog/jupyter.yap index abc85b04e..c82125571 100644 --- a/packages/python/yap_kernel/yap_ipython/prolog/jupyter.yap +++ b/packages/python/yap_kernel/yap_ipython/prolog/jupyter.yap @@ -4,6 +4,7 @@ * @brief JUpyter support. */ +:- yap_flag(gc_trace,verbose). % :- module( jupyter, % [jupyter_query/3, @@ -35,7 +36,11 @@ jupyter_cell( _Caller, _, Line ) :- !. jupyter_cell( Caller, _, Line ) :- Self := Caller.query, - python_query(Self,Line). + catch( + python_query(Self,Line), + E=error(A,B), + system_error(A,B) + ). restreams(call) :- streams(true). @@ -55,42 +60,37 @@ jupyter_consult(Cell) :- % Name = 'Inp', % stream_property(Stream, file_name(Name) ), % setup_call_cleanup( - open_mem_read_stream( Cell, Stream), - load_files(user:'jupyter cell',[stream(Stream)]). + catch( + ( + Options = [], + open_mem_read_stream( Cell, Stream), + load_files(user:'jupyter cell',[stream(Stream)| Options]) + ), + E=error(A,B), + (close(Stream), system_error(A,B)) + ), + fail. +jupyter_consult(_Cell). blank(Text) :- + atom(Text), + !, atom_codes(Text, L), maplist( code_type(space), L). - -:- dynamic cell_stream/1. +blank(Text) :- + string(Text), + !, + string_codes(Text, L), + maplist( code_type(space), L). streams(false) :- - nb_setval(jupyter_cell, false), - retract(cell_stream(S)), - close(S), - fail. -streams(false). + close(user_input), + close(user_output), + close(user_error). streams(true) :- - streams( false ), - nb_setval(jupyter_cell, true), -% \+ current_stream('/python/input',_,_), open('/python/input', read, Input, [alias(user_input),bom(false),script(false)]), - assert( cell_stream( Input) ), - set_prolog_flag(user_input,Input), - fail. -streams(true) :- -% \+ current_stream('/python/sys.stdout',_,_), open('/python/sys.stdout', append, Output, [alias(user_output)]), - set_prolog_flag(user_output, Output), - assert( cell_stream( Output) ), - fail. -streams(true) :- - % \+ current_stream('/python/sys.stderr',_,_), - open('/python/sys.stderr', append, Error, [alias(user_error)]), - assert( cell_stream( Error) ), - set_prolog_flag(user_error, Error), - fail. -streams(true). + open('/python/sys.stderr', append, Error, [alias(user_error)]). ready(_Self, Line ) :- blank( Line ), diff --git a/packages/python/yap_kernel/yap_ipython/prolog/verify.yap b/packages/python/yap_kernel/yap_ipython/prolog/verify.yap new file mode 100644 index 000000000..e951d38bf --- /dev/null +++ b/packages/python/yap_kernel/yap_ipython/prolog/verify.yap @@ -0,0 +1,62 @@ +/** + * @file jupyter.yap4py + * + * @brief JUpyter support. + */ + + + % :- module( verify, + % [all_clear/4, + % errors/2, + % ready/2, +s % completion/2, + % ] +%% ). +:- use_module(library(hacks)). + +:- use_module(library(lists)). +:- use_module(library(maplist)). + +:- use_module(library(python)). +:- use_module(library(yapi)). + +:- python_import(sys). + +p_errors( Errors, Cell) :- + blank( Cell ), + !. +p_errors( Errors, Cell) :- + no_errors( Errors , Cell ). + +no_errors( _Errors , Text ) :- + blank(Text). +no_errors( Errors , Text ) :- + setup_call_cleanup( + open_esh( Errors , Text, Stream), + esh(Errors , Stream), + close_esh( Errors , Stream ) + ). + +syntax(_Errors , E) :- writeln(user_error, E), fail. +syntax(Errors , error(syntax_error(Cause),info(between(_,LN,_), _FileName, CharPos, Details))) :- + Errors.errors := [t(Cause,LN,CharPos,Details)] + Errors.errors, + !. +syntax(_Errors , E) :- throw(E). + +open_esh(_Errors , Text, Stream) :- + open_mem_read_stream( Text, Stream ). + +esh(Errors , Stream) :- + repeat, + catch( + read_clause(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ), + Error, + syntax(Errors , Error) + ), + Cl == end_of_file, + !. + + + +close_esh( _Errors , Stream ) :- + close(Stream). diff --git a/packages/python/yap_kernel/yap_ipython/yapi.py b/packages/python/yap_kernel/yap_ipython/yapi.py index 8169da61a..562f2bd34 100644 --- a/packages/python/yap_kernel/yap_ipython/yapi.py +++ b/packages/python/yap_kernel/yap_ipython/yapi.py @@ -510,10 +510,9 @@ class YAPRun: def __init__(self, shell): self.shell = shell - self.yapeng = Engine() + self.yapeng = JupyterEngine() global engine engine = self.yapeng - self.yapeng.goal(use_module(library("jupyter")),True) self.query = None self.os = None self.it = None @@ -573,7 +572,6 @@ class YAPRun: except Exception as e: sys.stderr.write('Exception after', self.bindings, '\n') has_raised = True - self.yapeng.mgoal(streams(False),"user", True) return False,[] @@ -709,6 +707,7 @@ class YAPRun: self.shell.displayhook.exec_result = self.result has_raised = False try: + self.yapeng.mgoal(streams(True),"user", True) self.bindings = dicts = [] if cell.strip('\n \t'): #create a Trace object, telling it what to ignore, and whether to @@ -725,17 +724,17 @@ class YAPRun: # run the new command using the given tracer # # tracer.runfunc(f,self,cell,state) - self.yapeng.mgoal(streams(True),"user", True) self.jupyter_query( cell ) - self.yapeng.mgoal(streams(False),"user", True) # state = tracer.runfunc(jupyter_query( self, cell ) ) self.shell.last_execution_succeeded = True self.result.result = (True, dicts) - + except Exception as e: has_raised = True self.result.result = False + self.yapeng.mgoal(streams(False),"user", True) + self.yapeng.mgoal(streams(False),"user", True) self.shell.last_execution_succeeded = not has_raised # Reset this so later displayed values do not modify the @@ -771,7 +770,7 @@ class YAPRun: else: taken = l0-(i-1) n = s[i+1:].strip() - s = s[:i-1] + s = s[:i] if n: its = 0 for ch in n: diff --git a/packages/real/CMakeLists.txt b/packages/real/CMakeLists.txt index 0151bee32..a05d633dd 100644 --- a/packages/real/CMakeLists.txt +++ b/packages/real/CMakeLists.txt @@ -2,30 +2,12 @@ # PROJECT ( YAP_REAL C ) -# -# - This module locates an installed R distribution. -# -# Defines the following: -# R_COMMAND - Path to R command -# R_HOME - Path to 'R home', as reported by R -# R_INCLUDE_DIR - Path to R include directory -# R_LIBRARY_BASE - Path to R library -# R_LIBRARY_BLAS - Path to Rblas / blas library -# R_LIBRARY_LAPACK - Path to Rlapack / lapack library -# R_LIBRARY_READLINE - Path to readline library -# R_LIBRARIES - Array of: R_LIBRARY_BASE, R_LIBRARY_BLAS, R_LIBRARY_LAPACK, R_LIBRARY_BASE [, R_LIBRARY_READLINE] -# -# VTK_R_HOME - (deprecated, use R_HOME instead) Path to 'R home', as reported by R -# -# Variable search order: -# 1. Attempt to locate and set R_COMMAND -# If unsuccessful, generate error and prompt user to manually set R_COMMAND -# 2. Use R_COMMAND to set R_HOME -# 3. Locate other libraries in the priority: -# 1. Within a user-built instance of R at R_HOME -# 2. Within an installed instance of R -# 3. Within external system libraries -# + +# LIBR_FOUND +# LIBR_HOME +# LIBR_INCLUDE_DIRS +# LIBR_DOC_DIR +# LIBR_LIBRARIES if (R_LIBRARIES AND R_INCLUDE_DIR) set_package_properties(R PROPERTIES diff --git a/packages/swig/yap.i b/packages/swig/yap.i index 5f0390274..fca51c2b4 100644 --- a/packages/swig/yap.i +++ b/packages/swig/yap.i @@ -40,6 +40,7 @@ class YAPEngine; extern "C"{ #include "Yap.h" +X_API extern Term YAP_MkCharPTerm( char *n); #ifdef SWIGPYTHON diff --git a/packages/udi/utarray.h b/packages/udi/utarray.h index 0c1e59b5b..415652439 100644 --- a/packages/udi/utarray.h +++ b/packages/udi/utarray.h @@ -95,7 +95,7 @@ typedef struct { #define utarray_push_back(a,p) do { \ utarray_reserve(a,1); \ if ((a)->icd.copy) { (a)->icd.copy( _utarray_eltptr(a,(a)->i++), p); } \ - else { memcpy(_utarray_eltptr(a,(a)->i++), p, (a)->icd.sz); }; \ + else { memmove(_utarray_eltptr(a,(a)->i++), p, (a)->icd.sz); }; \ } while(0) #define utarray_pop_back(a) do { \ @@ -123,7 +123,7 @@ typedef struct { ((a)->i - (j))*((a)->icd.sz)); \ } \ if ((a)->icd.copy) { (a)->icd.copy( _utarray_eltptr(a,j), p); } \ - else { memcpy(_utarray_eltptr(a,j), p, (a)->icd.sz); }; \ + else { memmove(_utarray_eltptr(a,j), p, (a)->icd.sz); }; \ (a)->i++; \ } while(0) @@ -142,7 +142,7 @@ typedef struct { (a)->icd.copy(_utarray_eltptr(a,j+_ut_i), _utarray_eltptr(w,_ut_i)); \ } \ } else { \ - memcpy(_utarray_eltptr(a,j), _utarray_eltptr(w,0), \ + memmove(_utarray_eltptr(a,j), _utarray_eltptr(w,0), \ utarray_len(w)*((a)->icd.sz)); \ } \ (a)->i += utarray_len(w); \ diff --git a/packages/yap-lbfgs/liblbfgs-1.10/lib/lbfgs.c b/packages/yap-lbfgs/liblbfgs-1.10/lib/lbfgs.c index 30ffcf2ab..6fbd2242d 100644 --- a/packages/yap-lbfgs/liblbfgs-1.10/lib/lbfgs.c +++ b/packages/yap-lbfgs/liblbfgs-1.10/lib/lbfgs.c @@ -239,7 +239,7 @@ void lbfgs_free(lbfgsfloatval_t *x) void lbfgs_parameter_init(lbfgs_parameter_t *param) { - memcpy(param, &_defparam, sizeof(*param)); + memmove(param, &_defparam, sizeof(*param)); } int lbfgs( diff --git a/pl/absf.yap b/pl/absf.yap index 58d56817d..df1967057 100755 --- a/pl/absf.yap +++ b/pl/absf.yap @@ -302,8 +302,7 @@ absolute_file_name(File0,File) :- !, F. '$cat_file_name'(File, S) --> - {string(File), string_to_codes(File, S) }, - !, + {string(File), string_codes(File, S) }, S. diff --git a/pl/boot.yap b/pl/boot.yap index 94ebc41d8..46287f3cb 100644 --- a/pl/boot.yap +++ b/pl/boot.yap @@ -121,9 +121,11 @@ print_message(L,E) :- ). '$undefp0'([M|G], _Action) :- - stream_property( loop_stream, file_name(F)), - stream_property( loop_stream, line_number(L)), - format(user_error,'~a:~d error undefined: call to ~w~n',[F,L,M:G]), + stream_property( loop_stream, [file_name(F), line_number(L)]), + format(user_error,'~a:~d error undefined:',[F,L]), + fail + ; + format(user_error,' call to ~w~n',[M:G]), fail. :- '$undefp_handler'('$undefp0'(_,_),prolog). @@ -262,6 +264,7 @@ initialize_prolog :- :- c_compile( 'preds.yap' ). :- c_compile( 'modules.yap' ). :- c_compile( 'grammar.yap' ). +:- c_compile( 'protect.yap' ). :- ['absf.yap']. @@ -314,11 +317,7 @@ initialize_prolog :- :- multifile prolog:'$system_predicate'/2. -:- ['protect.yap']. - -version(yap,[6,4]). - -:- op(1150,fx,(mode)). +:- '$opdec'(1150,fx,(mode),prolog). :- dynamic 'extensions_to_present_answer'/1. diff --git a/pl/bootlists.yap b/pl/bootlists.yap index 2c209af51..69beade81 100644 --- a/pl/bootlists.yap +++ b/pl/bootlists.yap @@ -7,8 +7,6 @@ * @{ */ -:- system_module( '$_lists', [], []). - :- set_prolog_flag(source, true). % source. % memberchk(+Element, +Set) diff --git a/pl/consult.yap b/pl/consult.yap index 6cb1e38b9..c00331f1d 100644 --- a/pl/consult.yap +++ b/pl/consult.yap @@ -220,8 +220,10 @@ SWI-compatible option where if _Autoload_ is `true` undefined % compilation_mode(compact,source,assert_all) => implemented % register(true, false) => implemented % -load_files(Files,Opts) :- - '$load_files'(Files,Opts,load_files(Files,Opts)). +load_files(Files0,Opts) :- + '$yap_strip_module'(Files0,M,Files), + '$load_files'(Files,M,Opts,M:load_files(Files,Opts)). + '$lf_option'(autoload, 1, false). '$lf_option'(derived_from, 2, false). @@ -232,7 +234,14 @@ load_files(Files,Opts) :- '$lf_option'(qcompile, 7, Current) :- '__NB_getval__'('$qcompile', Current, Current = never). '$lf_option'(silent, 8, _). -'$lf_option'(skip_unix_header, 9, true). +'$lf_option'(skip_unix_header, 9, Skip) :- + stream_property(Stream,[alias(loop_stream),tty(TTy),reposition(Rep)]), + ( Rep == true + -> + (TTy = true -> Skip = false ; Skip = true) + ; + Skip = false + ). '$lf_option'(compilation_mode, 10, Flag) :- current_prolog_flag(source, YFlag), ( YFlag == false -> Flag = compact ; Flag = source ). @@ -271,42 +280,70 @@ load_files(Files,Opts) :- '$lf_option'(Op, Id, _), setarg( Id, TOpts, Val ). -'$load_files'(Files, Opts, Call) :- - ( '__NB_getval__'('$lf_status', OldTOpts, fail), nonvar(OldTOpts) -> - '$lf_opt'(autoload, OldTOpts, OldAutoload) - ; - '$lf_option'(last_opt, LastOpt), - functor( OldTOpts, opt, LastOpt ), - '$lf_opt'('$context_module', OldTOpts, user) - ), - '$lf_option'(last_opt, LastOpt), - functor( TOpts, opt, LastOpt ), - ( source_location(ParentF, Line) -> true ; ParentF = user_input, Line = -1 ), - '$lf_opt'('$location', TOpts, ParentF:Line), - '$lf_opt'('$files', TOpts, Files), - '$lf_opt'('$call', TOpts, Call), - '$lf_opt'('$options', TOpts, Opts), - '$lf_opt'('$parent_topts', TOpts, OldTOpts), - '$process_lf_opts'(Opts,TOpts,Files,Call), - '$lf_default_opts'(1, LastOpt, TOpts), - '$lf_opt'(stream, TOpts, Stream), - ( nonvar(Stream) -> - '$set_lf_opt'('$from_stream', TOpts, true ) - ; - '$check_files'(Files,load_files(Files,Opts)) - ), - '$check_use_module'(Call,UseModule), - '$lf_opt'('$use_module', TOpts, UseModule), - '$current_module'(M0), - ( '$lf_opt'(autoload, TOpts, Autoload), - var(Autoload) -> - Autoload = OldAutoload - ; - true - ), - % make sure we can run consult - '$init_consult', - '$lf'(Files, M0, Call, TOpts). +'$load_files'([user], M,Opts, Call) :- + current_input(S), + '$load_files__'(user, M, [stream(S)|Opts], Call). +'$load_files'(user, M,Opts, Call) :- + current_input(S), + '$load_files__'(user, M, [stream(S)|Opts], Call). +'$load_files'([-user], M,Opts, Call) :- + current_input(S), + '$load_files__'(user, M, [consult(reconsult),stream(S)|Opts], Call). +'$load_files'(-user, M,Opts, Call) :- + current_input(S), + '$load_files__'(user, M, [consult(reconsult),stream(S)|Opts], Call). +'$load_files'([user_input], M,Opts, Call) :- + current_input(S), + '$load_files__'(user_input, M, [stream(S)|Opts], Call). +'$load_files'(user_input, M,Opts, Call) :- + current_input(S), + '$load_files__'(user_input, M, [stream(S)|Opts], Call). +'$load_files'([-user_input], M,Opts, Call) :- + current_input(S), + '$load_files__'(user_input, M, [consult(reconsult),stream(S)|Opts], Call). +'$load_files'(-user_input, M,Opts, Call) :- + '$load_files__'(user_input, M, [consult(reconsult),stream(S)|Opts], Call). +'$load_files'(Files, M, Opts, Call) :- + '$load_files__'(Files, M, Opts, Call). +'$load_files__'(Files, M, Opts, Call) :- + '$lf_option'(last_opt, LastOpt), + ( '__NB_getval__'('$lf_status', OldTOpts, fail), + nonvar(OldTOpts) + -> + '$lf_opt'(autoload, OldTOpts, OldAutoload), + '$lf_opt'('$context_module', OldTOpts, OldContextModule) + ; + current_prolog_flag(autoload, OldAutoload), + functor( OldTOpts, opt, LastOpt ), + '$lf_opt'(autoload, OldTOpts, OldAutoload), + '$lf_opt'('$context_module', OldTOpts, OldContextModule) + ), + functor( TOpts, opt, LastOpt ), + ( source_location(ParentF, Line) -> true ; ParentF = user_input, Line = -1 ), + '$lf_opt'('$location', TOpts, ParentF:Line), + '$lf_opt'('$files', TOpts, Files), + '$lf_opt'('$call', TOpts, Call), + '$lf_opt'('$options', TOpts, Opts), + '$lf_opt'('$parent_topts', TOpts, OldTOpts), + '$process_lf_opts'(Opts,TOpts,Files,Call), + '$lf_default_opts'(1, LastOpt, TOpts), + '$lf_opt'(stream, TOpts, Stream), + ( nonvar(Stream) -> + '$set_lf_opt'('$from_stream', TOpts, true ) + ; + '$check_files'(Files,load_files(Files,Opts)) + ), + '$check_use_module'(Call,UseModule), + '$lf_opt'('$use_module', TOpts, UseModule), + ( '$lf_opt'(autoload, TOpts, Autoload), + var(Autoload) -> + Autoload = OldAutoload + ; + true + ), + % make sure we can run consult + '$init_consult', + '$lf'(Files, M, Call, TOpts). '$check_files'(Files, Call) :- var(Files), !, @@ -428,32 +465,12 @@ load_files(Files,Opts) :- '$lf'(V,_,Call, _ ) :- var(V), !, '$do_error'(instantiation_error,Call). '$lf'([], _, _, _) :- !. -'$lf'(M:X, _, Call, TOpts) :- !, - ( - atom(M) - -> - '$lf'(X, M, Call, TOpts) - ; - '$do_error'(type_error(atom,M),Call) - ). '$lf'([F|Fs], Mod, Call, TOpts) :- !, % clean up after each consult ( '$lf'(F,Mod,Call, TOpts), fail; '$lf'(Fs, Mod, Call, TOpts), fail; true ). -'$lf'(user, Mod, Call, TOpts) :- - !, - stream_property( S, alias( user_input )), - '$set_lf_opt'('$from_stream', TOpts, true), - '$set_lf_opt'( stream , TOpts, S), - '$lf'(S, Mod, Call, TOpts). -'$lf'(user_input, Mod, Call, TOpts ) :- - !, - stream_property( S, alias( user_input )), - '$set_lf_opt'('$from_stream', TOpts, true), - '$set_lf_opt'( stream , TOpts, S), - '$lf'(S, Mod, Call, TOpts). '$lf'(File, Mod, Call, TOpts) :- '$lf_opt'(stream, TOpts, Stream), b_setval('$user_source_file', File), @@ -544,10 +561,10 @@ When the files are not module files, ensure_loaded/1 loads them _F_ must be a list containing the names of the files to load. */ ensure_loaded(Fs) :- - '$load_files'(Fs, [if(not_loaded)],ensure_loaded(Fs)). + load_files(Fs, [if(not_loaded)]). compile(Fs) :- - '$load_files'(Fs, [], compile(Fs)). + load_files(Fs, []). /** @pred [ _F_ ] @@ -581,9 +598,9 @@ consult(Fs) :- '$consult'(Fs,Module) :- current_prolog_flag(language_mode, iso), % SICStus Prolog compatibility !, - '$load_files'(Module:Fs,[],consult(Fs)). + load_files(Module:Fs,[]). '$consult'(Fs, Module) :- - '$load_files'(Module:Fs,[consult(consult)],consult(Fs)). + load_files(Module:Fs,[consult(consult)]). /** @@ -616,7 +633,7 @@ Example: */ reconsult(Fs) :- - '$load_files'(Fs, [], reconsult(Fs)). + load_files(Fs, []). /* exo_files(+ _Files_) @@ -636,7 +653,7 @@ different forms of indexing, as shown in @cite x. */ exo_files(Fs) :- - '$load_files'(Fs, [consult(exo), if(not_loaded)], exo_files(Fs)). + load_files(Fs, [consult(exo), if(not_loaded)]). /** @@ -667,7 +684,7 @@ YAP implements load_db/1 as a two-step non-optimised process. First, db_files/1 itself is just a call to load_files/2. */ db_files(Fs) :- - '$load_files'(Fs, [consult(db), if(not_loaded)], exo_files(Fs)). + load_files(Fs, [consult(db), if(not_loaded)]). '$csult'(Fs, _M) :- @@ -677,9 +694,9 @@ db_files(Fs) :- !. '$csult'(Fs, M) :- '$extract_minus'(Fs, MFs), !, - '$load_files'(M:MFs,[],[M:Fs]). + load_files(M:MFs,[]). '$csult'(Fs, M) :- - '$load_files'(M:Fs,[consult(consult)],[M:Fs]). + load_files(M:Fs,[consult(consult)]). '$extract_minus'([], []). '$extract_minus'([-F|Fs], [F|MFs]) :- @@ -1099,7 +1116,7 @@ just goes through every loaded file and verifies whether reloading is needed. make :- recorded('$lf_loaded','$lf_loaded'(F1,_M,reconsult,_,_,_,_),_), - '$load_files'(F1, [if(changed)],make), + load_files(F1, [if(changed)]), fail. make. @@ -1260,11 +1277,11 @@ use_module(M,F,Is) :- '$use_module'(M,M1,F,Is) :- nonvar(F), !, ( var(M) -> - '$load_files'(M1:F, [if(not_loaded),must_be_module(true),imports(Is)], use_module(M,F,Is)), + load_files(M1:F, [if(not_loaded),must_be_module(true),imports(Is)]), absolute_file_name( F, F1, [expand(true),file_type(prolog)] ), recorded('$module','$module'(F1,M,_,_,_),_) ; -'$load_files'(M1:F, [if(not_loaded),must_be_module(true),imports(Is)], use_module(M,F,Is)) +load_files(M1:F, [if(not_loaded),must_be_module(true),imports(Is)], use_module(M,F,Is)) ). '$use_module'(M,M1,F,Is) :- nonvar(M), !, @@ -1272,11 +1289,11 @@ use_module(M,F,Is) :- ( recorded('$module','$module'(F0,M,_,_,_),_) -> - '$load_files'(M1:F0, [if(not_loaded),must_be_module(true),imports(Is)], use_module(M,F,Is)) + load_files(M1:F0, [if(not_loaded),must_be_module(true),imports(Is)]) ; nonvar(F0) -> - '$load_files'(M1:F, [if(not_loaded),must_be_module(true),imports(Is)], use_module(M,F,Is)) + load_files(M1:F, [if(not_loaded),must_be_module(true),imports(Is)]) ; '$do_error'(instantiation_error,use_module(M,F,Is)) ). diff --git a/pl/directives.yap b/pl/directives.yap index 21d403bc1..38540758b 100644 --- a/pl/directives.yap +++ b/pl/directives.yap @@ -45,7 +45,6 @@ '$include'/2, '$initialization'/1, '$initialization'/2, - '$load_files'/3, '$require'/2, '$set_encoding'/1, '$use_module'/3]). @@ -176,23 +175,23 @@ considered. '$exec_directive'(set_prolog_flag(F,V), _, _, _, _) :- set_prolog_flag(F,V). '$exec_directive'(ensure_loaded(Fs), _, M, _, _) :- - '$load_files'(M:Fs, [if(changed)], ensure_loaded(Fs)). + load_files(M:Fs, [if(changed)]). '$exec_directive'(char_conversion(IN,OUT), _, _, _, _) :- char_conversion(IN,OUT). '$exec_directive'(public(P), _, M, _, _) :- '$public'(P, M). '$exec_directive'(compile(Fs), _, M, _, _) :- - '$load_files'(M:Fs, [], compile(Fs)). + load_files(M:Fs, []). '$exec_directive'(reconsult(Fs), _, M, _, _) :- - '$load_files'(M:Fs, [], reconsult(Fs)). + load_files(M:Fs, []). '$exec_directive'(consult(Fs), _, M, _, _) :- - '$load_files'(M:Fs, [consult(consult)], consult(Fs)). + load_files(M:Fs, [consult(consult)]). '$exec_directive'(use_module(F), _, M, _, _) :- use_module(M:F). '$exec_directive'(reexport(F), _, M, _, _) :- - '$load_files'(M:F, [if(not_loaded), silent(true), reexport(true),must_be_module(true)], reexport(F)). + load_files(M:F, [if(not_loaded), silent(true), reexport(true),must_be_module(true)]). '$exec_directive'(reexport(F,Spec), _, M, _, _) :- - '$load_files'(M:F, [if(changed), silent(true), imports(Spec), reexport(true),must_be_module(true)], reexport(F, Spec)). + load_files(M:F, [if(changed), silent(true), imports(Spec), reexport(true),must_be_module(true)]). '$exec_directive'(use_module(F, Is), _, M, _, _) :- use_module(M:F, Is). '$exec_directive'(use_module(Mod,F,Is), _, _, _, _) :- diff --git a/pl/errors.yap b/pl/errors.yap index 38190aa2b..27819fb48 100644 --- a/pl/errors.yap +++ b/pl/errors.yap @@ -57,7 +57,7 @@ Errors are terms of the form: * Generate a system error _Error_, informing the possible cause _Cause_. * */ -system_error(Type,Goal) :- +prolog:system_error(Type,Goal) :- '$do_error'(Type,Goal). diff --git a/pl/hacks.yap b/pl/hacks.yap index 0b0c299cd..62692dbed 100644 --- a/pl/hacks.yap +++ b/pl/hacks.yap @@ -232,9 +232,9 @@ beautify_hidden_goal('$process_directive'(Gs,_Mode,_VL),prolog) --> [(:- Gs)]. beautify_hidden_goal('$loop'(Stream,Option),prolog) --> [execute_load_file(Stream, consult=Option)]. -beautify_hidden_goal('$load_files'(Files,Opts,?),prolog) --> - [load_files(Files,Opts)]. -beautify_hidden_goal('$load_files'(_,_,Name),prolog) --> +beautify_hidden_goal('$load_files'(Files,M,Opts,?),prolog) --> + [load_files(M:Files,Opts)]. +beautify_hidden_goal('$load_files'(_,_,_,Name),prolog) --> [Name]. beautify_hidden_goal('$reconsult'(Files,Mod),prolog) --> [reconsult(Mod:Files)]. diff --git a/pl/imports.yap b/pl/imports.yap index fea7ba8d0..665f4f675 100644 --- a/pl/imports.yap +++ b/pl/imports.yap @@ -9,6 +9,11 @@ /** * @ingroup ModuleBuiltins * @{ + * + * YAP follows the following protovol: + * - predicate is in current module; + * - predicate is in user + * - predicate will be autoloaded, SWI style. */ :- '$mk_dynamic'('$parent_module'(_,_),prolog). @@ -22,7 +27,6 @@ '$pred_exists'(G, user). % autoload '$get_undefined_predicates'(G, ImportingMod, G0, ExportingMod) :- - recorded('$dialect',swi,_), prolog_flag(autoload, true), prolog_flag(unknown, OldUnk, fail), ( @@ -38,6 +42,9 @@ '$get_undefined_predicates'(G, ImportingMod, G0, ExportingMod) :- '$parent_module'(ImportingMod,ExportingModI), '$continue_imported'(ExportingMod, ExportingModI, G0, G). +'$get_undefined_predicates'(G, _ImportingMod, G0, ExportingMod) :- + yap_flag(default_parent_module,ExportingModI), + '$continue_imported'(ExportingMod, ExportingModI, G0, G). '$get_undefined_pred'(G, ImportingMod, G0, ExportingMod) :- '$get_undefined_predicates'(G, ImportingMod, G0, ExportingMod), diff --git a/pl/init.yap b/pl/init.yap index c7c1bcb89..330bc76c4 100644 --- a/pl/init.yap +++ b/pl/init.yap @@ -33,17 +33,20 @@ nb_setval('$chr_toplevel_show_store',false). '$init_consult' :- - set_value('$open_expands_filename',true), - nb_setval('$assert_all',off), - nb_setval('$if_level',0), - nb_setval('$endif',off), - nb_setval('$initialization_goals',off), - nb_setval('$included_file',[]), - nb_setval('$loop_streams',[]), - \+ '$undefined'('$init_preds',prolog), - '$init_preds', - fail. -'$init_consult'. + set_value('$open_expands_filename',true), + nb_setval('$assert_all',off), + nb_setval('$if_level',0), + nb_setval('$endif',off), + nb_setval('$initialization_goals',off), + nb_setval('$included_file',[]), + nb_setval('$loop_streams',[]), + ( + '$undefined'('$init_preds',prolog) + -> + true + ; + '$init_preds' + ). '$init_win_graphics' :- '$undefined'(window_title(_,_), system), !. diff --git a/pl/messages.yap b/pl/messages.yap index effdc541b..7e6115c98 100644 --- a/pl/messages.yap +++ b/pl/messages.yap @@ -198,10 +198,9 @@ compose_message( halt, _Level) --> !, % syntax error. compose_message(error(E, Exc), Level) --> - { '$show_consult_level'(LC), '$print_exception'(Exc) - }, + { '$show_consult_level'(LC) }, location(error(E, Exc), Level, LC), - main_message(error(E,Exc) , Level, LC ), + main_message(error(E,Exc) , Level, LC ), c_goal( error(E, Exc), Level ), caller( error(E, Exc), Level ), extra_info( error(E, Exc), Level ), @@ -257,39 +256,28 @@ location(style_check(A,LN,FileName,B ), Level , LC) --> display_consulting( FileName, Level,style_check(A,LN,FileName,B ), LC ), [ '~a:~d:0 ~a ' - [FileName,LN,Level] ] . location( error(_,Info), Level, LC ) --> - { '$error_descriptor'(Info, Desc) }, + + { '$error_descriptor'(Info, Desc) }, { - '$query_exception'(prologPredFile, Desc, File), - '$query_exception'(prologPredLine, Desc, FilePos), - '$query_exception'(prologPredModule, Desc, M), - '$query_exception'(prologPredName, Desc, Na), - '$query_exception'(prologPredArity, Desc, Ar) + query_exception(prologPredFile, Desc, File), + query_exception(prologPredLine, Desc, FilePos), + query_exception(prologPredModule, Desc, M), + query_exception(prologPredName, Desc, Na), + query_exception(prologPredArity, Desc, Ar) }, !, display_consulting( File, Level, Info, LC ), - [ '~s:~d:0 ~a in ~s:~s/~d:'-[File, FilePos,Level,M,Na,Ar] ]. + [ '~a:~d:0 ~a in ~a:~a/~d:'-[File, FilePos,Level,M,Na,Ar] ]. location( error(_,Info), Level, LC ) --> { '$error_descriptor'(Info, Desc) }, { - '$query_exception'(prologPredFile, Desc, File), - '$query_exception'(prologPredLine, Desc, FilePos), - '$query_exception'(prologPredModule, Desc, M), - '$query_exception'(prologPredName, Desc, Na), - '$query_exception'(prologPredArity, Desc, Ar) - }, - !, - display_consulting( File, Level, Info, LC ), - [ '~s:~d:0 ~a in ~s:~s/~d:'-[File, FilePos,Level,M,Na,Ar] ]. -location( error(_,Info), Level, LC ) --> - { '$error_descriptor'(Info, Desc) }, - { - '$query_exception'(errorFile, Desc, File), - '$query_exception'(errorLine, Desc, FilePos), - '$query_exception'(errorFunction, Desc, F) + query_exception(errorFile, Desc, File), + query_exception(errorLine, Desc, FilePos), + query_exception(errorFunction, Desc, F) }, !, display_consulting( File, Level, Info, LC ), - [ '~s:~d:0 ~a in ~s():'-[File, FilePos,Level,F] ]. + [ '~a:~d:0 ~a in ~a():'-[File, FilePos,Level,F] ]. location( _Ball, _Level, _LC ) --> []. @@ -307,6 +295,10 @@ main_message( error(syntax_error(Msg),info(between(L0,LM,LF),_Stream, _Pos, Term [' ~a: failed_processing syntax error term ~q' - [Level,Term]], [nl] ). +main_message( error(syntax_error(_Msg), Info), Level, LC ) --> + !, + [' ~a: syntax error ~s' - [Level,Msg]], + [nl]. main_message(style_check(singleton(SVs),_Pos,_File,P), _Level, _LC) --> !, % {writeln(ci)}, @@ -354,8 +346,8 @@ main_message(error(uninstantiation_error(T),_), Level, _LC) --> display_consulting( F, Level, Info, LC) --> { LC > 0, '$error_descriptor'(Info, Desc), - '$query_exception'(prologParserFile, Desc, F0), - '$query_exception'(prologarserLine, Desc, L), + query_exception(prologParserFile, Desc, F0), + query_exception(prologarserLine, Desc, L), F \= F0 }, !, [ '~a:~d:0: ~a raised at:'-[F0,L,Level], nl ]. @@ -370,7 +362,7 @@ display_consulting(_F, _, _, _LC) --> caller( Info, _) --> { '$error_descriptor'(Info, Desc) }, - ({ '$query_exception'(errorGoal, Desc, Call), + ({ query_exception(errorGoal, Desc, Call), Call = M:(H :- G) } -> @@ -384,26 +376,26 @@ caller( Info, _) --> ; [] ), - { '$query_exception'(prologPredFile, Desc, File), + { query_exception(prologPredFile, Desc, File), File \= [], - '$query_exception'(prologPredLine, Desc, FilePos), - '$query_exception'(prologPredModule, Desc, M), - '$query_exception'(prologPredName, Desc, Na), - '$query_exception'(prologPredArity, Desc, Ar) + query_exception(prologPredLine, Desc, FilePos), + query_exception(prologPredModule, Desc, M), + query_exception(prologPredName, Desc, Na), + query_exception(prologPredArity, Desc, Ar) }, !, [nl], - ['~*| raised from ~a:~q:~d, ~a:~d:0: '-[10,M,Na,Ar,File, FilePos]], + ['~*| ~q:~d:0 ~a:~q'-[10,File, FilePos,M,Na,Ar]], [nl]. caller( _, _) --> []. c_goal( Info, Level ) --> { '$error_descriptor'(Info, Desc) }, - { '$query_exception'(errorFile, Desc, File), + { query_exception(errorFile, Desc, File), Func \= [], - '$query_exception'(errorFunction, Desc, File), - '$query_exception'(errorLine, Desc, Line) + query_exception(errorFunction, Desc, File), + query_exception(errorLine, Desc, Line) }, !, ['~*|~a raised at C-function ~a() in ~a:~d:0: '-[10, Level, Func, File, Line]], @@ -632,7 +624,7 @@ domain_error(Domain, Opt) --> extra_info( error(_,Extra), _ ) --> { - '$query_exception'(prologPredFile, Extra, Msg), + query_exception(prologPredFile, Extra, Msg), Msg \= [] }, !, @@ -982,8 +974,9 @@ confusing to YAP (who will process the error?). So we write this small stub to ensure everything os ok */ + +:- dynamic in/0. /* -/*:- dynamic in/0. prolog:print_message(Severity, Msg) :- \+ in, assert(in), @@ -991,7 +984,7 @@ prolog:print_message(Severity, Msg) :- ( prolog:print_message(Severity, Msg), fail; stop_low_level_trace, retract(in) - ).*/ + ). */ prolog:print_message(Severity, Msg) :- ( @@ -1043,7 +1036,7 @@ prolog:print_message(Severity, Term) :- ), !. prolog:print_message(Severity, Term) :- - translate_message( Term, Severity, Lines0, [ end(Id)]), + translate_message( Term, Severity, Lines0, [ end(Id)]), Lines = [begin(Severity, Id)| Lines0], ( user:message_hook(Term, Severity, Lines) @@ -1057,8 +1050,14 @@ prolog:print_message(Severity, Term) :- prolog:print_message(_Severity, _Term) :- format(user_error,'failed to print ~w: ~w~n' ,[ _Severity, _Term]). -'$error_descriptor'( error(_,Info), Info ). +'$error_descriptor'( exception(Info), Info ). +query_exception(K0,[H|L],V) :- + (atom(K0) -> atom_to_string(K0, K) ; K = K0), + !, + lists:member(K=V,[H|L]). +query_exception(K,V) :- + '$query_exception'(K,V). /** @} diff --git a/pl/modules.yap b/pl/modules.yap index 5747add74..6aba25b45 100644 --- a/pl/modules.yap +++ b/pl/modules.yap @@ -201,8 +201,8 @@ The state of the module system after this error is undefined. **/ -use_module(F) :- '$load_files'(F, - [if(not_loaded),must_be_module(true)], use_module(F)). +use_module(F) :- load_files(F, + [if(not_loaded),must_be_module(true)]). /** @@ -235,7 +235,7 @@ Unfortunately it is still not possible to change argument order. **/ use_module(F,Is) :- - '$load_files'(F, [if(not_loaded),must_be_module(true),imports(Is)], use_module(F,Is)). + load_files(F, [if(not_loaded),must_be_module(true),imports(Is)]). '$module'(O,N,P,Opts) :- !, '$module'(O,N,P), diff --git a/pl/protect.yap b/pl/protect.yap index 23f8a6a8f..7d9bc46dd 100755 --- a/pl/protect.yap +++ b/pl/protect.yap @@ -36,12 +36,12 @@ */ -'$protect' :- +prolog:'$protect' :- '$all_current_modules'(M), ( sub_atom(M,0,1,_, '$') ; M= prolog; M= system ), new_system_module( M ), fail. -'$protect' :- +prolog:'$protect' :- '$current_predicate'(Name,M,P,_), '$is_system_module'(M), functor(P,Name,Arity), @@ -50,13 +50,13 @@ functor(P,Name,Arity), '$hide_predicate'(P,M), fail. -'$protect' :- +prolog:'$protect' :- current_atom(Name), sub_atom(Name,0,1,_, '$'), \+ '$visible'(Name), hide_atom(Name), fail. -'$protect'. +prolog:'$protect'. % hide all atoms who start by '$' diff --git a/swi/console/console.c b/swi/console/console.c index 141c00f46..19b487f9b 100755 --- a/swi/console/console.c +++ b/swi/console/console.c @@ -2225,7 +2225,7 @@ rlc_save_font_options(HFONT font, rlc_console_attr *attr) { LOGFONT lf; if ( GetObject(font, sizeof(lf), &lf) ) - { memcpy(attr->face_name, lf.lfFaceName, sizeof(attr->face_name)-1); + { memmove(attr->face_name, lf.lfFaceName, sizeof(attr->face_name)-1); attr->font_family = lf.lfPitchAndFamily; attr->font_size = lf.lfHeight; @@ -3803,7 +3803,7 @@ Dprint_lines(RlcData b, int from, int to) for( ; ; from = NextLine(b, from)) { TextLine tl = &b->lines[from]; - memcpy(buf, tl->text, tl->size); + memmove(buf, tl->text, tl->size); buf[tl->size] = EOS; Dprintf(_T("%03d: (0x%08x) \"%s\"\n"), from, tl->text, buf);