Example #1
0
/** get contents of the boolean array object */
REPC SEXP RgetBoolArrayCont(SEXP e) {
  SEXP ar;
  jarray o;
  int l;
  jboolean *ap;
  JNIEnv *env=getJNIEnv();

  profStart();
  if (e==R_NilValue) return e;
  if (TYPEOF(e)==EXTPTRSXP) {
    jverify(e);
    o=(jobject)EXTPTR_PTR(e);
  } else
    error("invalid object parameter");
  _dbg(rjprintf("RgetBoolArrayCont: jarray %x\n",o));
  if (!o) return R_NilValue;
  l=(int)(*env)->GetArrayLength(env, o);
  _dbg(rjprintf(" convert bool array of length %d\n",l));
  if (l<0) return R_NilValue;
  ap=(jboolean*)(*env)->GetBooleanArrayElements(env, o, 0);
  if (!ap)
    error("cannot obtain boolean array contents");
  PROTECT(ar=allocVector(LGLSXP,l));
  { /* jboolean = byte, logical = int, need to convert */
    int i = 0;
    while (i < l) {
      LOGICAL(ar)[i] = ap[i];
      i++;
    }
  }
  UNPROTECT(1);
  (*env)->ReleaseBooleanArrayElements(env, o, ap, 0);
  _prof(profReport("RgetBoolArrayCont[%d]:",o));
  return ar;
}
Example #2
0
/** get contents of the object array in the form of list of ext. pointers */
REPC SEXP RgetObjectArrayCont(SEXP e) {
  SEXP ar;
  jarray o;
  int l,i;
  JNIEnv *env=getJNIEnv();

  profStart();
  if (e==R_NilValue) return R_NilValue;
  if (TYPEOF(e)==EXTPTRSXP) {
    jverify(e);
    o=(jobject)EXTPTR_PTR(e);
  } else
    error("invalid object parameter");
  _dbg(rjprintf("RgetObjectArrayCont: jarray %x\n",o));
  if (!o) return R_NilValue;
  l=(int)(*env)->GetArrayLength(env, o);
  _dbg(rjprintf(" convert object array of length %d\n",l));
  if (l<1) return R_NilValue;
  PROTECT(ar=allocVector(VECSXP,l));
  i=0;
  while (i<l) {
    jobject ae = (*env)->GetObjectArrayElement(env, o, i);
    _mp(MEM_PROF_OUT("  %08x LNEW object array element [%d]\n", (int) ae, i))
    SET_VECTOR_ELT(ar, i, j2SEXP(env, ae, 1));
    i++;
  }
  UNPROTECT(1);
  _prof(profReport("RgetObjectArrayCont[%d]:",o));
  return ar;
}
Example #3
0
/** get contents of the integer array object */
REPC SEXP RgetIntArrayCont(SEXP e) {
  SEXP ar;
  jarray o;
  int l;
  jint *ap;
  JNIEnv *env=getJNIEnv();

  profStart();
  if (e==R_NilValue) return e;
  if (TYPEOF(e)==EXTPTRSXP) {
    jverify(e);
    o=(jobject)EXTPTR_PTR(e);
  } else
    error("invalid object parameter");
  _dbg(rjprintf("RgetIntArrayCont: jarray %x\n",o));
  if (!o) return R_NilValue;
  l=(int)(*env)->GetArrayLength(env, o);
  _dbg(rjprintf(" convert int array of length %d\n",l));
  if (l<0) return R_NilValue;
  ap=(jint*)(*env)->GetIntArrayElements(env, o, 0);
  if (!ap)
    error("cannot obtain integer array contents");
  PROTECT(ar=allocVector(INTSXP,l));
  if (l>0) memcpy(INTEGER(ar),ap,sizeof(jint)*l);
  UNPROTECT(1);
  (*env)->ReleaseIntArrayElements(env, o, ap, 0);
  _prof(profReport("RgetIntArrayCont[%d]:",o));
  return ar;
}
Example #4
0
/** get contents of the object array in the form of int* */
SEXP jri_getStringArray(JNIEnv *env, jarray o) {
    SEXP ar;
    int l, i;
    const char *c;

    profStart();
    _dbg(rjprintf(" jarray %d\n",o));
    if (!o) return R_NilValue;
    l = (int)(*env)->GetArrayLength(env, o);
    _dbg(rjprintf("convert string array of length %d\n",l));
    PROTECT(ar = allocVector(STRSXP,l));
    for (i = 0; i < l; i++) {
	jobject sobj = (*env)->GetObjectArrayElement(env, o, i);
	c = 0;
	if (sobj) {
	    /* we could (should?) check the type here ...
	       if (!(*env)->IsInstanceOf(env, sobj, javaStringClass)) {
	       printf(" not a String\n");
	       } else
	    */
	    c = (*env)->GetStringUTFChars(env, sobj, 0);
	}
	if (!c)
	    SET_STRING_ELT(ar, i, R_NaString); /* this is probably redundant since the vector is pre-filled with NAs, but just in case ... */
	else {
	    SET_STRING_ELT(ar, i, mkCharUTF8(c));
	    (*env)->ReleaseStringUTFChars(env, sobj, c);
	}
    }
    UNPROTECT(1);
    _prof(profReport("RgetStringArrayCont[%d]:",o));
    return ar;
}
Example #5
0
    /**
     * Creates initial process tree
     */
    void ProcessManagerMac::createProcTree() {
        boost::recursive_mutex::scoped_lock lock( m_accessMutex );

        std::vector< kinfo_proc > procList;
        GetUnixProcesses( procList );

        _dbg("Mac Process count: %u!", procList.size());

        vector< kinfo_proc >::iterator it;
        vector< kinfo_proc >::iterator end_it = procList.end();

        // Creates a map with all processes that will be feed to m_processTree
        ProcessMap processMap;
        for ( it = procList.begin(); it != end_it; ++it ) {
            try {
                // Get the instantly available data
                pid_t pid = it->kp_proc.p_pid;
                pid_t ppid = it->kp_eproc.e_ppid;

                processMap[ pid ] = ProcessProperties();
                setProcessProperties( processMap[ pid ], pid, true, ppid, false, "" );
            } catch ( const std::exception & ex ) {
                _dbg("Exception while adding processes: %s", ex.what());
            }
        }

        boost::recursive_mutex::scoped_lock lock2( m_processTree.mutex() );
        m_processTree.clear();
        m_processTree.addConnectProcesses( processMap );

        //dumpTree();
    }
Example #6
0
/** get contents of the boolean array object into a logical R vector */
SEXP jri_getBoolArray(JNIEnv *env, jarray o) {
  SEXP ar;
  int l;
  jboolean *ap;

  profStart();
  _dbg(rjprintf(" jarray %d\n",o));
  if (!o) return R_NilValue;
  l=(int)(*env)->GetArrayLength(env, o);
  _dbg(rjprintf("convert boolean array of length %d into R bool\n",l));
  if (l<1) return R_NilValue;
  ap=(jboolean*)(*env)->GetBooleanArrayElements(env, o, 0);
  if (!ap) {
      jri_error("RgetBoolArrayCont: can't fetch array contents");
      return 0;
  }
  PROTECT(ar=allocVector(LGLSXP,l));
  {
    int i=0;
    int *lgl = LOGICAL(ar);
    while (i<l) { lgl[i]=ap[i]?1:0; i++; }
  }
  UNPROTECT(1);
  (*env)->ReleaseBooleanArrayElements(env, o, ap, 0);
  _prof(profReport("RgetBoolArrayCont[%d]:",o));
  return ar;
}
Example #7
0
/** get contents of the long array object (int) */
REPC SEXP RgetLongArrayCont(SEXP e) {
  SEXP ar;
  jarray o;
  int l;
  jlong *ap;
  JNIEnv *env=getJNIEnv();
	
  profStart();
  if (e==R_NilValue) return e;
  if (TYPEOF(e)==EXTPTRSXP) {
    jverify(e);
    o=(jobject)EXTPTR_PTR(e);
  } else
    error("invalid object parameter");
  _dbg(rjprintf("RgetLongArrayCont: jarray %d\n",o));
  if (!o) return R_NilValue;
  l=(int)(*env)->GetArrayLength(env, o);
  _dbg(rjprintf(" convert long array of length %d\n",l));
  if (l<0) return R_NilValue;
  ap=(jlong*)(*env)->GetLongArrayElements(env, o, 0);
  if (!ap)
    error("cannot obtain long contents");
  PROTECT(ar=allocVector(REALSXP,l));
  { /* long must be coerced into double .. we use just a cast for each element, bad idea? */
    int i=0;
    while (i<l) { REAL(ar)[i]=(double)ap[i]; i++; }
  }
  UNPROTECT(1);
  (*env)->ReleaseLongArrayElements(env, o, ap, 0);
  _prof(profReport("RgetLongArrayCont[%d]:",o));
  return ar;
}
Example #8
0
/* jobject to SEXP encoding - 0.2 and earlier use INTSXP */
SEXP j2SEXP(JNIEnv *env, jobject o, int releaseLocal) {
  if (!env) error("Invalid Java environment in j2SEXP");
  if (o) {
    jobject go = makeGlobal(env, o);
    _mp(MEM_PROF_OUT("R %08x RNEW %08x\n", (int) go, (int) o))
    if (!go)
      error("Failed to create a global reference in Java.");
    _dbg(rjprintf(" j2SEXP: %lx -> %lx (release=%d)\n", (long)o, (long)go, releaseLocal));
    if (releaseLocal)
      releaseObject(env, o);
    o=go;
  }
  
  {
    SEXP xp = R_MakeExternalPtr(o, R_NilValue, R_NilValue);

#ifdef RJ_DEBUG
    {
      JNIEnv *env=getJNIEnv();
      jstring s=callToString(env, o);
      const char *c="???";
      if (s) c=(*env)->GetStringUTFChars(env, s, 0);
      _dbg(rjprintf("New Java object [%s] reference %lx (SEXP@%lx)\n", c, (long)o, (long)xp));
      if (s) {
	(*env)->ReleaseStringUTFChars(env, s, c);
	releaseObject(env, s);
      }
    }
#endif

    R_RegisterCFinalizerEx(xp, JRefObjectFinalizer, TRUE);
    return xp;
  }
}
Example #9
0
HIDE void deserializeSEXP(SEXP o) {
  _dbg(rjprintf("attempt to deserialize %p (clCL=%p, oCL=%p)\n", o, clClassLoader, oClassLoader));
  SEXP s = EXTPTR_PROT(o);
  if (TYPEOF(s) == RAWSXP && EXTPTR_PTR(o) == NULL) {
    JNIEnv *env = getJNIEnv();
    if (env && clClassLoader && oClassLoader) {
      jbyteArray ser = newByteArray(env, RAW(s), LENGTH(s));
      if (ser) {
	jmethodID mid = (*env)->GetMethodID(env, clClassLoader, "toObject", "([B)Ljava/lang/Object;");
	if (mid) {
	  jobject res = (*env)->CallObjectMethod(env, oClassLoader, mid, ser);
	  if (res) {
	    jobject go = makeGlobal(env, res);
	    _mp(MEM_PROF_OUT("R %08x RNEW %08x\n", (int) go, (int) res))
	    if (go) {
	      _dbg(rjprintf(" - succeeded: %p\n", go));
	      /* set the deserialized object */
	      EXTPTR_PTR(o) = (SEXP) go;
	      /* Note: currently we don't remove the serialized content, because it was created explicitly using .jcache to allow repeated saving. Once this is handled by a hook, we shall remove it. However, to assure compatibility TAG is always NULL for now, so we do clear the cache if TAG is non-null for future use. */
	      if (EXTPTR_TAG(o) != R_NilValue) {
		/* remove the serialized raw vector */
		SETCDR(o, R_NilValue); /* Note: this is abuse of the API since it uses the fact that PROT is stored in CDR */
	      }
	    }
	  }
	}
	releaseObject(env, ser);
      }
    }    
Example #10
0
c_rpc_server::~c_rpc_server() {
	_dbg("rpc server destructor");
	m_io_service.stop();
	_dbg("io service stopped, join thread");
	m_thread.join();
	_dbg("thread joined");
}
Example #11
0
void c_rpc_server::c_session::read_handler_hmac(const boost::system::error_code &error, std::size_t bytes_transferred) {
	_dbg("readed " << bytes_transferred << " bytes of hmac authenticator");
	_dbg("authenticate message");
	if (error) {
		_dbg("asio error " << error.message());
		delete_me();
		return;
	}
	int ret = crypto_auth_hmacsha512_verify(m_hmac_authenticator.data(),
	                                        reinterpret_cast<const unsigned char *>(m_received_data.data()),
	                                        m_received_data.size(),
	                                        m_hmac_key.data()
	);
	if (ret == -1) {
		_warn("hmac authentication error");
		delete_me();
		return;
	}
	assert(ret == 0);
	try {
		execute_rpc_command(m_received_data);
	} catch (const std::exception &e) {
		_erro( "exception read_handler " << e.what());
		_erro( "close connection\n" );
		delete_me();
		return;
	}
}
Example #12
0
SEXP jri_getSEXPLArray(JNIEnv *env, jarray o) {
    SEXP ar;
    int l,i=0;
    jlong *ap;
    
    profStart();
    _dbg(rjprintf(" jarray %d\n",o));
    if (!o) return R_NilValue;
    l=(int)(*env)->GetArrayLength(env, o);
    _dbg(rjprintf("convert SEXPL array of length %d\n",l));
    if (l<1) return R_NilValue;
    ap=(jlong*)(*env)->GetLongArrayElements(env, o, 0);
    if (!ap) {
        jri_error("getSEXPLArray: can't fetch array contents");
        return 0;
    }
    PROTECT(ar=allocVector(VECSXP,l));
    while (i<l) {
        SET_VECTOR_ELT(ar, i, L2SEXP(ap[i]));
        i++;
    }
    UNPROTECT(1);
    (*env)->ReleaseLongArrayElements(env, o, ap, 0);
    _prof(profReport("jri_getSEXPLArray[%d]:",o));
    return ar;
}
Example #13
0
c_rpc_server::c_rpc_server(const unsigned short port)
:
	m_io_service(),
	m_acceptor(m_io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string("127.0.0.1"), port)),
	m_socket(m_io_service),
	m_thread(),
	m_hmac_key()
{
	m_hmac_key.fill(0x42); // TODO load this from conf file
	// start waiting for new connection
	m_acceptor.async_accept(m_socket, [this](boost::system::error_code error) {
		accept_handler(error);
	});
	_dbg("Starting RPC server thread");
	m_thread = std::thread([this]() {
		_dbg("RPC thread start");
		try {
			boost::system::error_code ec;
			_dbg("io_service run");
			m_io_service.run(ec);
			_dbg("end of io_service run");
			if (ec)
				_dbg("error code " << ec.message());
			_dbg("io_service reset");
			m_io_service.reset();
		} catch (const std::exception &e) {
			_dbg("io_service exception" << e.what());
		} catch (...) {
			_dbg("catch unhandled exception");
		}

		_dbg("RPC thread stop");
	}); // lambda
}
Example #14
0
Resultado::operator string() const {
	os out;
	_dbg(out,id);
	_dbg(out,J);
	_dbg(out,CR);
	_dbg(out,cluster.size());
	for (size_t i = 0; i < cluster.size(); i++) {
		_dbg(out,i);
		_print(out,cluster[i]);
	}
	return out.str();
}
Example #15
0
void c_rpc_server::c_session::read_handler_data(const boost::system::error_code &error, std::size_t bytes_transferred) {
	_dbg("readed " << bytes_transferred << " bytes of data");
	if (error) {
		_dbg("asio error " << error.message());
		delete_me();
		return;
	}
	// parsing message
	_dbg("received message " << m_received_data);
	async_read(m_socket, boost::asio::buffer(&m_hmac_authenticator.at(0), m_hmac_authenticator.size()),
		[this](const boost::system::error_code &error, std::size_t bytes_transferred) {
			read_handler_hmac(error, bytes_transferred);
	});
}
Example #16
0
/**
 ** Analogue: fputs().
 ** Sends two commands to the child: first the "real command", then the
 ** "tag (trivial) command".
 ** Uses a "lazy fork" concept; we don't actually start the child
 ** at the time of the child_open() call but instead when the first cmd
 ** is sent. This means a program which employs a dispatcher, for instance,
 ** can do a child_open() in the main function, pass the handle off to
 ** all the routines it dispatches to, and child_close() before exiting
 ** without worrying about which of those functions will actually need
 ** the coprocess.  If some of them don't need it, they won't send it
 ** any commands and will incur no fork/exec overhead.
 **/
int
child_puts(char *s, CHILD *handle, AV* perl_out_array, AV* perl_err_array)
{
   int n;

   if (handle == NULL)
      handle = mru_handle;
   if ((mru_handle = handle) == NULL)
      return 0;
   if (handle->cph_pid == 0) {
      if (_cp_start_child(handle) != 0) {
	 fprintf(stderr, "can't start child %s\n",  handle->cph_cmd);
	 exit(1);
      }
      /* Add file descriptors to poll vector. */
      poll_add_fd( fileno(handle->cph_back),
                   NPOLL_TXT, bck_read, NULL, handle );
      poll_add_fd( fileno(handle->cph_err),
                   NPOLL_TXT, err_read, NULL, handle );
   }

   /* Save Perl array references for access from callbacks. */
   handle->cph_out_array = perl_out_array;
   handle->cph_err_array = perl_err_array;

   _dbg(F,L,1, "-->> %s", s);

   /** set error count to 0 for new command **/
   handle->cph_errs = 0;

   /** send the cmd down the pipe to the child **/
   if ((n = fputs(s, handle->cph_down)) == EOF)
      return EOF;
   /** be helpful and add a newline if there isn't one **/
   if (strrchr(s, '\n') != endof(s) - 1)
      if (fputc('\n', handle->cph_down) == EOF)
	 return EOF;
   /** send the tag cmd **/
   _dbg(F,L,4, "-->> [TAG]");
   if (fputs(handle->cph_tag, handle->cph_down) == EOF)
      return EOF;
   handle->cph_pending = TRUE;
   _dbg(F,L,4, "pending ...");

   /** poll **/
   poll_rcv( NPOLL_NO_TIMEOUT ); 

   return n;
}
Example #17
0
jarray jri_putDoubleArray(JNIEnv *env, SEXP e)
{
    if (TYPEOF(e)!=REALSXP) return 0;
    _dbg(rjprintf(" real vector of length %d\n",LENGTH(e)));
    {
        unsigned len=LENGTH(e);
        jdoubleArray da=(*env)->NewDoubleArray(env,len);
        jdouble *dae;

        if (!da) {
            jri_error("newDoubleArray.new(%d) failed",len);
            return 0;
        }
        if (len>0) {
            dae=(*env)->GetDoubleArrayElements(env, da, 0);
            if (!dae) {
                (*env)->DeleteLocalRef(env,da);
                jri_error("newDoubleArray.GetDoubleArrayElements failed");
                return 0;
            }
            memcpy(dae,REAL(e),sizeof(jdouble)*len);
            (*env)->ReleaseDoubleArrayElements(env, da, dae, 0);
        }
        return da;
    }
}
Example #18
0
static void JRefObjectFinalizer(SEXP ref) {
    if (java_is_dead) return;

  if (TYPEOF(ref)==EXTPTRSXP) {
    JNIEnv *env=getJNIEnv();
    jobject o = R_ExternalPtrAddr(ref);

#ifdef RJ_DEBUG
    {
      jstring s=callToString(env, o);
      const char *c="???";
      if (s) c=(*env)->GetStringUTFChars(env, s, 0);
      _dbg(rjprintf("Finalizer releases Java object [%s] reference %lx (SEXP@%lx)\n", c, (long)o, (long)ref));
      if (s) {
	(*env)->ReleaseStringUTFChars(env, s, c);
	releaseObject(env, s);
      }
    }
#endif

    if (env && o) {
      /* _dbg(rjprintf("  finalizer releases global reference %lx\n", (long)o);) */
      _mp(MEM_PROF_OUT("R %08x FIN\n", (int)o))
      releaseGlobal(env, o);
    }
  }
}
Example #19
0
/**
 ** Send a signal to the coprocess.  Remember, 'kill' is a misnomer;
 ** it's just a signal.
 **/
int
child_kill(CHILD *handle, int signo)
{
   UPDATE_HANDLE(handle, mru_handle, 0);
   _dbg(F,L,4, "sending signal %d to pid: %d", signo, handle->cph_pid);
   return kill(handle->cph_pid, signo);
}
Example #20
0
jarray jri_putIntArray(JNIEnv *env, SEXP e)
{
    if (TYPEOF(e)!=INTSXP) return 0;
    _dbg(rjprintf(" integer vector of length %d\n",LENGTH(e)));
    {
        unsigned len=LENGTH(e);
        jintArray da=(*env)->NewIntArray(env,len);
        jint *dae;

        if (!da) {
            jri_error("newIntArray.new(%d) failed",len);
            return 0;
        }
        
        if (len>0) {
            dae=(*env)->GetIntArrayElements(env, da, 0);
            if (!dae) {
                (*env)->DeleteLocalRef(env,da);
                jri_error("newIntArray.GetIntArrayElements failed");
                return 0;
            }
            memcpy(dae,INTEGER(e),sizeof(jint)*len);
            (*env)->ReleaseIntArrayElements(env, da, dae, 0);
        }
        return da;
    }
}
Example #21
0
 void KfWindowCache::invalidateEntry() {
     if( m_cache.end() != m_currentCacheEntry ) {
         _dbg("INVALIDATE: 0x%x", m_currentCacheEntry->first);
         m_cache.erase(m_currentCacheEntry);
         m_currentCacheEntry = m_cache.end();
     }
 }
Example #22
0
    set< pair<pid_t, std::string> > ProcessTree::fetchDescendants(pid_t pid) const {
        /// Lock
        boost::recursive_mutex::scoped_lock lock(m_accessMutex);

        set< pair<pid_t, string> > retSet;
        if(0 == m_pidToIdMap.count(pid)) {
            _dbg("NO SUCH PID %d! ", pid);
            return retSet;
        }

        // The pid must exist (see count(key) above)
        ProcId procId;
        map<pid_t, ProcId>::const_iterator iter = m_pidToIdMap.find( pid );
        if (iter != m_pidToIdMap.end()) {
            procId = iter->second;
        } else {
            // TODO handle error;
        }

        fetchDescendants_sub(retSet, procId);

        _qldbg("-----:::: ");
        for( set< pair<pid_t, string> >::iterator it = retSet.begin(); it != retSet.end(); ++it ) {
            _qldbg("%s ",it->second.c_str());
        }
        _qdbg("");

        return retSet;
    }
Example #23
0
jarray jri_putByteArray(JNIEnv *env, SEXP e)
{
    if (TYPEOF(e) != RAWSXP) return 0;
    _dbg(rjprintf(" raw vector of length %d\n", LENGTH(e)));
    {
        unsigned len = LENGTH(e);
        jbyteArray da = (*env)->NewByteArray(env,len);
        jbyte *dae;

        if (!da) {
            jri_error("newByteArray.new(%d) failed",len);
            return 0;
        }
        
        if (len > 0) {
            dae = (*env)->GetByteArrayElements(env, da, 0);
            if (!dae) {
                (*env)->DeleteLocalRef(env, da);
                jri_error("newByteArray.GetByteArrayElements failed");
                return 0;
            }
            memcpy(dae, RAW(e), len);
            (*env)->ReleaseByteArrayElements(env, da, dae, 0);
        }
        return da;
    }
}
Example #24
0
jarray jri_putSEXPLArray(JNIEnv *env, SEXP e)
{
    _dbg(rjprintf(" general vector of length %d\n",LENGTH(e)));
    {
        unsigned len=LENGTH(e);
        jlongArray da=(*env)->NewLongArray(env,len);
        jlong *dae;
        
        if (!da) {
            jri_error("newLongArray.new(%d) failed",len);
            return 0;
        }
        
        if (len>0) {
            int i=0;
            
            dae=(*env)->GetLongArrayElements(env, da, 0);
            if (!dae) {
                (*env)->DeleteLocalRef(env,da);
                jri_error("newLongArray.GetLongArrayElements failed");
                return 0;
            }
            while (i<len) {
                dae[i] = SEXP2L(VECTOR_ELT(e, i));
                i++;
            }
            (*env)->ReleaseLongArrayElements(env, da, dae, 0);
        }
        return da;
    }
}
Example #25
0
/* TODO; use the mid_RJavaTools_getFieldTypeName method ID instead */
static char *findFieldSignature(JNIEnv *env, jclass cls, const char *fnam) {
  char *detsig = 0;
  jstring s = newString(env, fnam);
  if (s) {
    jobject f = (*env)->CallObjectMethod(env, cls, mid_getField, s);
    _mp(MEM_PROF_OUT("  %08x LNEW object getField result value\n", (int) f))
    if (f) {
      jobject fcl = (*env)->CallObjectMethod(env, f, mid_getType);
      _mp(MEM_PROF_OUT("  %08x LNEW object getType result value\n", (int) f))
      if (fcl) {
	jobject fcns = (*env)->CallObjectMethod(env, fcl, mid_getName);
	releaseObject(env, fcl);
	if (fcns) {
	  const char *fcn = (*env)->GetStringUTFChars(env, fcns, 0);
	  detsig = classToJNI(fcn);
	  _dbg(Rprintf("class '%s' -> '%s' sig\n", fcn, detsig));
	  (*env)->ReleaseStringUTFChars(env, fcns, fcn);
	  releaseObject(env, fcns);
	  /* fid = (*env)->FromReflectedField(env, f); */
	}
      } else
	releaseObject(env, fcl);
      releaseObject(env, f);
    }
    releaseObject(env, s);
  }
  return detsig;
}
Example #26
0
/**
 * log_msg - Write log message into lp_diag log file
 *
 * @fmt	format string to printf()
 * @...	additional argument
 */
void
log_msg(const char *fmt, ...)
{
	int	rc;
	int     len = 0;
	char    buf[LP_ERROR_LOG_MAX];
	va_list ap;

#ifndef LPD_DEBUG
	/* In order to make testing easier we will not print time in
	 * debug version of lp_diag.
	 */
	if (lp_error_log_fd != STDOUT_FILENO) {
		len = insert_time(buf, LP_ERROR_LOG_MAX);
		len += snprintf(buf + len, LP_ERROR_LOG_MAX - len, ": ");
	}
#endif

	/* Add the actual message */
	va_start(ap, fmt);
	len += vsnprintf(buf + len, LP_ERROR_LOG_MAX - len, fmt, ap);
	if (len < 0 || len >= LP_ERROR_LOG_MAX) {
		dbg("Insufficient buffer size");
		va_end(ap);
		return;
	}
	va_end(ap);

	/* Add ending punctuation */
	len += snprintf(buf + len, LP_ERROR_LOG_MAX - len, ".");

	if (lp_error_log_fd == -1) {
		dbg("Log file \"%s\" is not available", lp_error_log_file);
		_dbg(buf);
		return;
	}

	_dbg(buf);

	/* reformat the new message */
	len = reformat_msg(buf, LP_ERROR_LOG_MAX);
	rc = write(lp_error_log_fd, buf, len);
	if (rc == -1)
		dbg("Write to log file \"%s\" failed", lp_error_log_file);
}
Example #27
0
int err_read( void* handle, char* buf, int len ){
  if( len ){
    /*
     * Interrupt handling doesn't work quite right. As yet undiagnosed
     * but this code is left in because it's no worse than not having it.
     */
    if( !strncmp( buf, "Interrupt", 9 ) ){
      _dbg(F,L,3, "interrupted end of cmd from %s", ((CHILD*)handle)->cph_cmd );
      return NPOLL_RET_IDLE;
    } else {
      _dbg(F,L,2, "<<== '%.*s'", len, buf);
      Perl_av_push( aTHX_ ((CHILD*)handle)->cph_err_array , Perl_newSVpv( aTHX_ buf, len ) );
      return NPOLL_CONTINUE;
    }
  } else {
    return NPOLL_RET_IDLE;
  }
}
Example #28
0
/**
 * rotate_log_file - Check log file size and rotate if required.
 *
 * @lp_log_file	log file name
 *
 * Returns :
 *	nothing
 */
static void
rotate_log_file(char *lp_log_file)
{
	int	rc;
	int	dir_fd;
	char	*dir_name;
	char	lp_log_file0[PATH_MAX];
	struct	stat sbuf;

	rc = stat(lp_log_file, &sbuf);
	if (rc == -1) {
		dbg("Cannot stat log file to rotate logs");
		return;
	}

	if (sbuf.st_size <= LP_ERRD_LOGSZ)
		return;

	_dbg("Rotating log file : %s", lp_log_file);
	snprintf(lp_log_file0, PATH_MAX, "%s0", lp_log_file);

	/* Remove old files */
	rc = stat(lp_log_file0, &sbuf);
	if (rc == 0) {
		if (unlink(lp_log_file0)) {
			dbg("Could not delete archive file %s "
			    "(%d: %s) to make a room for new archive."
			    " The new logs will be logged anyway.",
			    lp_log_file0, errno, strerror(errno));
			return;
		}
	}

	rc = rename(lp_log_file, lp_log_file0);
	if (rc == -1) {
		dbg("Could not archive log file %s to %s (%d: %s)",
		    lp_log_file, lp_log_file0, errno, strerror(errno));
		return;
	}

	dir_name = dirname(lp_log_file0);
	dir_fd = open(dir_name, O_RDONLY | O_DIRECTORY);
	if (dir_fd == -1) {
		dbg("Could not open log directory %s (%d: %s)",
		    dir_name, errno, strerror(errno));
		return;
	}

	/* sync log directory */
	rc = fsync(dir_fd);
	if (rc == -1)
		dbg("Could not sync log directory %s (%d: %s)",
		    dir_name, errno, strerror(errno));

	close(dir_fd);
}
Example #29
0
void
mlead_dump(void)
{
    mleak_mem_node_t    *pNode_act = 0;

    pthread_mutex_lock(&g_mleak_mutex);
    {
        pNode_act = g_mleak_dev.pNode_head;

        if( pNode_act )     _dbg("\n\nmemory leak:\n");

        while( pNode_act )
        {
            int             i;
            unsigned char   *pTmp = 0;

            if( pNode_act->verify_tag != MLEAK_VERIFY_TAG )
            {
                _err("error, get a dirty node !!\n");
                break;
            }

            _dbg("\tmalloc (ptr=0x%x, len=%u) at %s [#%u]\n",
                 pNode_act->pPtr, pNode_act->length, pNode_act->path, pNode_act->line_num);

            pTmp = (unsigned char*)((unsigned long)pNode_act + sizeof(mleak_mem_node_t));
            _dbg("\t  hex: ");
            for(i = 0; i < 12; i++)
            {
                if( i == 4 )    _dbg("\n\t\t");

                _dbg("%02x ", *(pTmp + i));
            }

            _dbg("...\n\t\t");
            pTmp = (unsigned char*)((unsigned long)pNode_act->pPtr + pNode_act->length);
            for(i = 0; i < (MLEAK_PROTECT_SIZE << 2); i++)
                _dbg("%02x ", *(pTmp + i));

            _dbg("\n");
            pNode_act = pNode_act->next;
        }
        _dbg("-------------- %s end\n", __FUNCTION__);
    }
    pthread_mutex_unlock(&g_mleak_mutex);
    return;
}
Example #30
0
void c_rpc_server::c_session::execute_rpc_command(const std::string &input_message) {
	try {
		nlohmann::json j = nlohmann::json::parse(input_message);
		const std::string cmd_name = j.begin().value();
		_dbg("cmd name " << cmd_name);
		// calling rpc function
		const std::string response = m_rpc_server_ptr->m_rpc_functions_map.at(cmd_name)(input_message);
		// serialize response
		assert(response.size() <= std::numeric_limits<uint16_t>::max());
		uint16_t size = static_cast<uint16_t>(response.size());
		m_write_data.resize(size + 2); ///< 2 first bytes for size
		m_write_data.at(0) = static_cast<char>(size >> 8);
		m_write_data.at(1) = static_cast<char>(size & 0xFF);
		for (size_t i = 0; i < response.size(); ++i)
			m_write_data.at(i + 2) = response.at(i);
		// send response

		_dbg("send packet");
		_dbg(m_write_data);
		std::array<unsigned char, crypto_auth_hmacsha512_BYTES> hash;
		int ret = crypto_auth_hmacsha512(hash.data(), reinterpret_cast<unsigned char *>(&m_write_data.at(2)), size, m_rpc_server_ptr->m_hmac_key.data());
		if (ret != 0) _throw_error(std::runtime_error("crypto_auth_hmacsha512 error"));
		_dbg("hmac");
		//for (const auto & byte : hash) std::cout << std::hex << "0x" << static_cast<int>(byte) << " ";
		//std::cout << std::dec << std::endl;
		std::array<boost::asio::const_buffer, 2> buffers = {
			{boost::asio::buffer(m_write_data.data(), m_write_data.size()),
			boost::asio::buffer(hash.data(), hash.size())}
		};
		m_socket.async_write_some(buffers,
			[this](const boost::system::error_code& error, std::size_t bytes_transferred) {
				write_handler(error, bytes_transferred);
		});
	}
	catch (const std::exception &e) {
		_erro( "exception in execute_rpc_command " << e.what() );
		_erro( "close connection\n" );
		delete_me();
		return;
	}
}