Ejemplo n.º 1
0
String debug_string_backtrace(bool skip, bool ignore_args /* = false */,
                              int64_t limit /* = 0 */) {
  Array bt;
  StringBuffer buf;
  bt = createBacktrace(BacktraceArgs()
                       .skipTop(skip)
                       .ignoreArgs(ignore_args)
                       .setLimit(limit));
  int i = 0;
  for (ArrayIter it = bt.begin(); !it.end(); it.next(), i++) {
    Array frame = it.second().toArray();
    buf.append('#');
    buf.append(i);
    if (i < 10) buf.append(' ');
    buf.append(' ');
    if (frame.exists(s_class)) {
      buf.append(frame->get(s_class).toString());
      buf.append(frame->get(s_type).toString());
    }
    buf.append(frame->get(s_function).toString());
    buf.append("(");
    if (!ignore_args) {
      bool first = true;
      for (ArrayIter argsIt(frame->get(s_args).toArray());
          !argsIt.end();
          argsIt.next()) {
        if (!first) {
          buf.append(", ");
        } else {
          first = false;
        }
        try {
          buf.append(argsIt.second().toString());
        } catch (FatalErrorException& fe) {
          buf.append(fe.getMessage());
        }
      }
    }
    buf.append(")");
    if (frame.exists(s_file)) {
      buf.append(" called at [");
      buf.append(frame->get(s_file).toString());
      buf.append(':');
      buf.append(frame->get(s_line).toString());
      buf.append(']');
    }
    buf.append('\n');
  }
  return buf.detach();
}
Ejemplo n.º 2
0
Variant HHVM_FUNCTION(shell_exec,
                      const String& cmd) {
  ShellExecContext ctx;
  FILE *fp = ctx.exec(cmd);
  if (!fp) return init_null();
  StringBuffer sbuf;
  sbuf.read(fp);
  auto ret = sbuf.detach();
  if (ret.empty() && !RuntimeOption::EnableHipHopSyntax) {
    // Match php5
    return init_null();
  }
  return ret;
}
Ejemplo n.º 3
0
bool UrlFile::open(CStrRef url, CStrRef mode) {
  if (strchr(mode, '+') || strchr(mode, 'a') || strchr(mode, 'w')) {
    std::string msg = "cannot open a url stream for write/append operation: ";
    msg += url.c_str();
    m_error = msg;
    return false;
  }
  HttpClient http(m_timeout, m_maxRedirect);
  StringBuffer response;

  HeaderMap *pHeaders = NULL;
  HeaderMap requestHeaders;
  if (!m_headers.empty()) {
    pHeaders = &requestHeaders;
    for (ArrayIter iter(m_headers); iter; ++iter) {
      requestHeaders[string(iter.first().toString().data())].
        push_back(iter.second().toString().data());
    }
  }

  int code;
  vector<String> responseHeaders;
  if (m_get) {
    code = http.get(url.c_str(), response, pHeaders, &responseHeaders);
  } else {
    code = http.post(url.c_str(), m_postData.data(), m_postData.size(),
                     response, pHeaders, &responseHeaders);
  }

  SystemGlobals *g = (SystemGlobals*)get_global_variables();
  Variant &r = g->GV(http_response_header);
  r = Array::Create();
  for (unsigned int i = 0; i < responseHeaders.size(); i++) {
    r.append(responseHeaders[i]);
  }

  if (code == 200) {
    int len = m_len;
    m_name = url;
    m_data = response.detach(len);
    m_len = len;
    m_malloced = true;
    return true;
  } else {
    m_error = http.getLastError().c_str();
    return false;
  }
}
Ejemplo n.º 4
0
char *CThorCodeContextBase::getDaliServers()
{
    StringBuffer dali;
    IGroup &group = queryCoven().queryComm().queryGroup();
    Owned<INodeIterator> coven = group.getIterator();
    bool first = true;
    ForEach(*coven)
    {
        if (first)
            first = false;
        else
            dali.append(',');
        coven->query().endpoint().getUrlStr(dali);
    }
    return dali.detach();
}
Ejemplo n.º 5
0
static String normalize_variable_name(const String& name) {
  StringBuffer sb;
  for (int i = 0; i < name.size(); i++) {
    char ch = name.charAt(i);
    if ((i > 0 && ch >= '0' && ch <= '9') ||
        (ch >= 'a' && ch <= 'z') ||
        (ch == '_')) {
      sb.append(ch);
    } else if (ch >= 'A' && ch <= 'Z') {
      sb.append((char)(ch + 'a' - 'A'));
    } else {
      sb.append('_');
    }
  }
  return sb.detach();
}
Ejemplo n.º 6
0
String debug_string_backtrace(bool skip, bool ignore_args /* = false */,
                              int limit /* = 0 */) {
  if (RuntimeOption::InjectedStackTrace) {
    Array bt;
    StringBuffer buf;
    bt = g_vmContext->debugBacktrace(skip, false, false, nullptr,
                                     ignore_args, limit);
    int i = 0;
    for (ArrayIter it = bt.begin(); !it.end(); it.next(), i++) {
      Array frame = it.second().toArray();
      buf.append('#');
      buf.append(i);
      if (i < 10) buf.append(' ');
      buf.append(' ');
      if (frame.exists(s_class)) {
        buf.append(frame->get(s_class).toString());
        buf.append(frame->get(s_type).toString());
      }
      buf.append(frame->get(s_function).toString());
      buf.append("(");
      if (!ignore_args) {
        bool first = true;
        for (ArrayIter it = frame->get(s_args).begin(); !it.end(); it.next()) {
          if (!first) {
            buf.append(", ");
          } else {
            first = false;
          }
          buf.append(it.second().toString());
        }
      }
      buf.append(")");
      if (frame.exists(s_file)) {
        buf.append(" called at [");
        buf.append(frame->get(s_file).toString());
        buf.append(':');
        buf.append(frame->get(s_line).toString());
        buf.append(']');
      }
      buf.append('\n');
    }
    return buf.detach();
  } else {
    StackTrace st;
    return String(st.toString());
  }
}
Ejemplo n.º 7
0
std::pair<bool,Variant>
DebuggerProxy::ExecutePHP(const std::string &php, String &output,
                          int frame, int flags) {
  TRACE(2, "DebuggerProxy::ExecutePHP\n");
  // Wire up stdout and stderr to our own string buffer so we can pass
  // any output back to the client.
  StringBuffer sb;
  StringBuffer *save = g_context->swapOutputBuffer(nullptr);
  DebuggerStdoutHook stdout_hook(sb);
  DebuggerLoggerHook stderr_hook(sb);
  g_context->setStdout(&stdout_hook);
  if (flags & ExecutePHPFlagsLog) {
    Logger::SetThreadHook(&stderr_hook);
  }
  SCOPE_EXIT {
    g_context->setStdout(nullptr);
    g_context->swapOutputBuffer(save);
    if (flags & ExecutePHPFlagsLog) {
      Logger::SetThreadHook(nullptr);
    }
  };
  String code(php.c_str(), php.size(), CopyString);
  // We're about to start executing more PHP. This is typically done
  // in response to commands from the client, and the client expects
  // those commands to send more interrupts since, of course, the
  // user might want to debug the code we're about to run. If we're
  // already processing an interrupt, enable signal polling around
  // the execution of the new PHP to ensure that we can handle
  // signals while doing so.
  //
  // Note: we must switch the thread mode to Sticky so we block
  // other threads which may hit interrupts while we're running,
  // since nested processInterrupt() calls would normally release
  // other threads on the way out.
  assertx(m_thread == (int64_t)Process::GetThreadId());
  ThreadMode origThreadMode = m_threadMode;
  switchThreadMode(Sticky, m_thread);
  if (flags & ExecutePHPFlagsAtInterrupt) enableSignalPolling();
  SCOPE_EXIT {
    if (flags & ExecutePHPFlagsAtInterrupt) disableSignalPolling();
    switchThreadMode(origThreadMode, m_thread);
  };
  auto const ret = g_context->evalPHPDebugger(code.get(), frame);
  output = sb.detach();
  return {ret.failed, ret.result};
}
Ejemplo n.º 8
0
/* Xml encode the passed string. */
String xdebug_xmlize(const char* string, size_t len) {
  StringBuffer out;
  for (size_t i = 0; i < len; ++i) {
    switch (string[i]) {
    case '&':  out.append("&amp;");   break;
    case '>':  out.append("&gt;");    break;
    case '<':  out.append("&lt;");    break;
    case '"':  out.append("&quot;");  break;
    case '\'': out.append("&#39;");   break;
    case '\n': out.append("&#10;");   break;
    case '\r': out.append("&#13;");   break;
    case '\0': out.append("&#0;");    break;
    default:   out.append(string[i]); break;
    }
  }
  return out.detach();
}
Ejemplo n.º 9
0
static void json_create_zval(Variant &z, StringBuffer &buf, int type) {
  switch (type) {
  case KindOfInt64:
    {
      const char *p = buf.data();
      ASSERT(p);
      if (p == NULL) {
        z = 0LL;
        return;
      }

      bool neg = (buf.charAt(0) == '-');

      int len = buf.size();
      if (neg) len--;
      if (len >= MAX_LENGTH_OF_LONG - 1) {
        if (len == MAX_LENGTH_OF_LONG - 1) {
          int cmp = strcmp(p + (neg ? 1 : 0), long_min_digits);
          if (!(cmp < 0 || (cmp == 0 && neg))) {
            z = strtod(p, NULL);
            return;
          }
        } else {
          z = strtod(p, NULL);
          return;
        }
      }
      z = strtoll(buf.data(), NULL, 10);
    }
    break;
  case KindOfDouble:
    z = buf.data() ? strtod(buf.data(), NULL) : 0.0;
    break;
  case KindOfString:
    z = buf.detach();
    buf.reset();
    break;
  case KindOfBoolean:
    z = (buf.data() && (*buf.data() == 't'));
    break;
  default:
    z = null;
    break;
  }
}
Ejemplo n.º 10
0
String PageletTransport::getResults(
  Array &headers,
  int &code,
  int64_t timeout_ms
) {
  {
    Lock lock(this);
    while (!m_done && m_pipeline.empty()) {
      if (timeout_ms > 0) {
        long seconds = timeout_ms / 1000;
        long long nanosecs = (timeout_ms % 1000) * 1000000;
        if (!wait(seconds, nanosecs)) {
          code = -1;
          return empty_string();
        }
      } else {
        wait();
      }
    }

    if (!m_pipeline.empty()) {
      // intermediate results do not have headers and code
      std::string ret = m_pipeline.front();
      m_pipeline.pop_front();
      code = 0;
      return ret;
    }
  }

  String response(m_response.c_str(), m_response.size(), CopyString);
  headers = Array::Create();
  for (HeaderMap::const_iterator iter = m_responseHeaders.begin();
       iter != m_responseHeaders.end(); ++iter) {
    for (unsigned int i = 0; i < iter->second.size(); i++) {
      StringBuffer sb;
      sb.append(iter->first);
      sb.append(": ");
      sb.append(iter->second[i]);
      headers.append(sb.detach());
    }
  }
  code = m_code;
  return response;
}
Ejemplo n.º 11
0
void StringBuffer::absorb(StringBuffer &buf) {
  if (empty()) {
    char *buffer = m_buffer;
    int size = m_size;

    m_buffer = buf.m_buffer;
    m_size = buf.m_size;
    m_pos = buf.m_pos;
#ifdef TAINTED
    propagate_tainting1_bufbuf( buf, *this );
#endif

    buf.m_buffer = buffer;
    buf.m_size = size;
    buf.reset();
  } else {
    append(buf.detach());
  }
}
Ejemplo n.º 12
0
void StringBuffer::absorb(StringBuffer &buf) {
  if (empty()) {
    TAINT_OBSERVER_REGISTER_ACCESSED(buf.getTaintDataRefConst());
    TAINT_OBSERVER_REGISTER_MUTATED(m_taint_data);

    char *buffer = m_buffer;
    int size = m_size;

    m_buffer = buf.m_buffer;
    m_size = buf.m_size;
    m_pos = buf.m_pos;

    buf.m_buffer = buffer;
    buf.m_size = size;
    buf.reset();
  } else {
    append(buf.detach());
  }
}
Ejemplo n.º 13
0
CachedUnit createUnitFromUrl(const StringData* const requestedPath,
                             const Native::FuncTable& nativeFuncs,
                             FileLoadFlags& flags) {
  auto const w = Stream::getWrapperFromURI(StrNR(requestedPath));
  StringBuffer sb;
  {
    // Stream wrappers can reenter PHP via user defined callbacks. Roll this
    // operation into a single event
    rqtrace::EventGuard trace{"STREAM_WRAPPER_OPEN"};
    rqtrace::DisableTracing disable;

    if (!w) return CachedUnit{};
    auto const f = w->open(StrNR(requestedPath), "r", 0, nullptr);
    if (!f) return CachedUnit{};
    sb.read(f.get());
  }
  OptLog ent;
  return createUnitFromString(requestedPath->data(), sb.detach(), nullptr, ent,
                              nativeFuncs, RepoOptions::defaults(), flags);
}
Ejemplo n.º 14
0
  String getResults(Array &headers, int &code) {
    {
      Lock lock(this);
      while (!m_done) wait();
    }

    String response(m_response.c_str(), m_response.size(), CopyString);
    headers = Array::Create();
    for (HeaderMap::const_iterator iter = m_responseHeaders.begin();
         iter != m_responseHeaders.end(); ++iter) {
      for (unsigned int i = 0; i < iter->second.size(); i++) {
        StringBuffer sb;
        sb.append(iter->first);
        sb.append(": ");
        sb.append(iter->second[i]);
        headers.append(sb.detach());
      }
    }
    code = m_code;
    return response;
  }
Ejemplo n.º 15
0
Variant f_stream_get_contents(CResRef handle, int maxlen /* = -1 */,
                              int offset /* = -1 */) {
  if (maxlen < -1) {
    throw_invalid_argument("maxlen: %d", maxlen);
    return false;
  }

  if (maxlen == 0) {
    return String();
  }

  File *file = handle.getTyped<File>(false /* nullOkay */,
                                     true /* badTypeOkay */);
  if (!file) {
    throw_invalid_argument(
      "stream_get_contents() expects parameter 1 to be a resource");
    return false;
  }

  if (offset >= 0 && !file->seek(offset, SEEK_SET) ) {
    raise_warning("Failed to seek to position %d in the stream", offset);
    return false;
  }

  String ret;
  if (maxlen != -1) {
    ret = String(maxlen, ReserveString);
    char *buf = ret.bufferSlice().ptr;
    maxlen = file->readImpl(buf, maxlen);
    if (maxlen < 0) {
      return false;
    }
    ret.setSize(maxlen);
  } else {
    StringBuffer sb;
    sb.read(file);
    ret = sb.detach();
  }
  return ret;
}
Ejemplo n.º 16
0
void StringBuffer::absorb(StringBuffer& buf) {
  if (empty()) {
    StringData* str = m_str;

    m_str = buf.m_str;
    m_len = buf.m_len;
    m_cap = buf.m_cap;

    buf.m_str = str;
    if (str) {
      buf.m_len = str->size();
      buf.m_cap = str->capacity();
    } else {
      buf.m_len = 0;
      buf.m_cap = 0;
    }
    buf.clear();
    return;
  }

  append(buf.detach());
}
Ejemplo n.º 17
0
bool CmdExtension::processList(DebuggerProxy *proxy) {
  IDebuggable::InfoVec info;

  Array exts = Extension::GetLoadedExtensions();
  typedef std::set<std::string, string_lessi> sorted_iset;
  sorted_iset names;
  for (ArrayIter iter(exts); iter; ++iter) {
    names.insert(iter.second().toString().data());
  }
  for (sorted_iset::const_iterator iter = names.begin();
       iter != names.end(); ++iter) {
    Extension *ext = Extension::GetExtension(*iter);
    ASSERT(ext);
    if (ext) {
      int support = ext->debuggerSupport();
      string line;
      line += (support & IDebuggable::SupportInfo) ? "Yes     " : "        ";
      line += (support & IDebuggable::SupportDump) ? "Yes     " : "        ";
      line += (support & IDebuggable::SupportVerb) ? "Yes     " : "        ";
      line += ext->getVersion();
      IDebuggable::Add(info, iter->c_str(), line);
    }
  }
  int nameLen;
  String body = DebuggerClient::FormatInfoVec(info, &nameLen);
  int hrLen = nameLen + 42;
  if (hrLen > DebuggerClient::LineWidth) hrLen = DebuggerClient::LineWidth;

  StringBuffer sb;
  for (int i = 0; i < hrLen; i++) sb.append(BOX_H); sb.append("\n");
  sb.append(StringUtil::Pad("Name\\Support", nameLen));
  sb.append("Info    Dump    Verb    Version\n");
  for (int i = 0; i < hrLen; i++) sb.append(BOX_H); sb.append("\n");
  sb.append(body);
  for (int i = 0; i < hrLen; i++) sb.append(BOX_H); sb.append("\n");

  m_out = sb.detach();
  return proxy->send(this);
}
Ejemplo n.º 18
0
Variant DebuggerProxy::ExecutePHP(const std::string &php, String &output,
                                  bool log, int frame) {
  TRACE(2, "DebuggerProxy::ExecutePHP\n");
  Variant ret;
  StringBuffer sb;
  StringBuffer *save = g_context->swapOutputBuffer(nullptr);
  g_context->setStdout(append_stdout, &sb);
  if (log) {
    Logger::SetThreadHook(append_stderr, &sb);
  }
  try {
    String code(php.c_str(), php.size(), CopyString);
    g_vmContext->evalPHPDebugger((TypedValue*)&ret, code.get(), frame);
  } catch (InvalidFunctionCallException &e) {
    sb.append(Debugger::ColorStderr(String(e.what())));
    sb.append(Debugger::ColorStderr(
              "You may also need to connect to a host "
              "(e.g., machine connect localhost)."));
  } catch (Exception &e) {
    sb.append(Debugger::ColorStderr(String(e.what())));
  } catch (Object &e) {
    try {
      sb.append(Debugger::ColorStderr(e.toString()));
    } catch (BadTypeConversionException &e) {
      sb.append(Debugger::ColorStderr
                (String("(object without __toString() is thrown)")));
    }
  } catch (...) {
    sb.append(Debugger::ColorStderr(String("(unknown exception was thrown)")));
  }
  g_context->setStdout(nullptr, nullptr);
  g_context->swapOutputBuffer(save);
  if (log) {
    Logger::SetThreadHook(nullptr, nullptr);
  }
  output = sb.detach();
  return ret;
}
Ejemplo n.º 19
0
bool CmdExtension::processList(DebuggerProxy &proxy) {
  IDebuggable::InfoVec info;

  Array exts = ExtensionRegistry::getLoaded();

  std::set<std::string, string_lessi> names;
  for (ArrayIter iter(exts); iter; ++iter) {
    names.insert(iter.second().toString().data());
  }
  for (auto const& name : names) {
    auto ext = ExtensionRegistry::get(name);
    assert(ext);
    if (ext) {
      int support = ext->debuggerSupport();
      std::string line;
      line += (support & IDebuggable::SupportInfo) ? "Yes     " : "        ";
      line += (support & IDebuggable::SupportDump) ? "Yes     " : "        ";
      line += (support & IDebuggable::SupportVerb) ? "Yes     " : "        ";
      line += ext->getVersion();
      IDebuggable::Add(info, name.c_str(), line);
    }
  }
  int nameLen;
  String body = DebuggerClient::FormatInfoVec(info, &nameLen);
  int hrLen = nameLen + 42;
  if (hrLen > DebuggerClient::LineWidth) hrLen = DebuggerClient::LineWidth;

  StringBuffer sb;
  for (int i = 0; i < hrLen; i++) sb.append(BOX_H); sb.append("\n");
  sb.append(StringUtil::Pad("Name\\Support", nameLen));
  sb.append("Info    Dump    Verb    Version\n");
  for (int i = 0; i < hrLen; i++) sb.append(BOX_H); sb.append("\n");
  sb.append(body);
  for (int i = 0; i < hrLen; i++) sb.append(BOX_H); sb.append("\n");

  m_out = sb.detach();
  return proxy.sendToClient(this);
}
Ejemplo n.º 20
0
String WddxPacket::wrapValue(const String& start,
                             const String& end,
                             const String& varValue,
                             const String& varName,
                             bool hasVarTag) {
  StringBuffer valueStr;

  if (hasVarTag) {
    valueStr.append("<var name='");
    valueStr.append(varName);
    valueStr.append("'>");
  }

  valueStr.append(start);
  valueStr.append(varValue);
  valueStr.append(end);

  if (hasVarTag) {
    valueStr.append("</var>");
  }

  return valueStr.detach();
}
Ejemplo n.º 21
0
bool TestExtProcess::test_proc_open_env_inh() {
    Array descriptorspec =
        CREATE_MAP3(0, CREATE_VECTOR2("pipe", "r"),
                    1, CREATE_VECTOR2("pipe", "w"),
                    2, CREATE_VECTOR3("file", "/tmp/error-output.txt", "a"));

    Variant pipes;
    g_context->setenv("inherit_me", "please");
    Variant process = f_proc_open("echo $inherit_me", descriptorspec, ref(pipes));
    VERIFY(!same(process, false));

    {
        File *f = pipes[1].toObject().getTyped<File>();
        VERIFY(f->valid());
        StringBuffer sbuf;
        sbuf.read(f);
        f->close();
        VS(sbuf.detach(), "please\n");
    }

    VS(f_proc_close(process.toObject()), 0);

    return Count(true);
}
Ejemplo n.º 22
0
bool TestExtNetwork::test_fsockopen() {
  {
    Variant f = f_fsockopen("facebook.com", 80);
    VERIFY(!same(f, false));
    f_fputs(f, "GET / HTTP/1.0\n\n");
    VERIFY(!f_fread(f, 15).toString().empty());
  }
  {
    Variant f = f_fsockopen("ssl://www.facebook.com", 443);
    VERIFY(!same(f, false));
    f_fwrite(f,
             "GET / HTTP/1.1\r\n"
             "Host: www.facebook.com\r\n"
             "Connection: Close\r\n"
             "\r\n");
    StringBuffer response;
    while (!same(f_feof(f), true)) {
      Variant line = f_fgets(f, 128);
      response.append(line.toString());
    }
    VERIFY(!response.detach().empty());
  }
  return Count(true);
}
Ejemplo n.º 23
0
String Eval::location_to_string(const Location *loc) {
  StringBuffer buf;
  buf.printf("%s:%d:%d", loc->file, loc->line1, loc->char1);
  return buf.detach();
}
Ejemplo n.º 24
0
PhpFile *FileRepository::checkoutFile(StringData *rname,
                                      const struct stat &s) {
  FileInfo fileInfo;
  PhpFile *ret = nullptr;
  String name(rname);
  bool isPlainFile = File::IsPlainFilePath(name);

  if (isPlainFile) {
    if (rname->data()[0] != '/') {
      name = String(SourceRootInfo::GetCurrentSourceRoot()) + name;
    }
    // Get the common fast path out of the way with as little locking
    // as possible: it's in the map and has not changed on disk
    ParsedFilesMap::const_accessor acc;
    if (s_files.find(acc, name.get()) && !acc->second->isChanged(s)) {
      TRACE(1, "FR fast path hit %s\n", rname->data());
      ret = acc->second->getPhpFile();
      return ret;
    }
  } else {
    // Do the read before we get the repo lock, since it will call into the
    // stream library and will needs its own locks.
    if (isAuthoritativeRepo()) {
      throw FatalErrorException(
        "including urls doesn't work in RepoAuthoritative mode"
      );
    }
    Stream::Wrapper* w = Stream::getWrapperFromURI(name);
    File* f = w->open(name, "r", 0, null_variant);
    if (!f) return nullptr;
    StringBuffer sb;
    sb.read(f);
    fileInfo.m_inputString = sb.detach();
    computeMd5(name.get(), fileInfo);
  }

  TRACE(1, "FR fast path miss: %s\n", rname->data());
  const StringData *n = makeStaticString(name.get());

  PhpFile* toKill = nullptr;
  SCOPE_EXIT {
    // run this after acc is destroyed (and its lock released)
    if (toKill) toKill->decRefAndDelete();
  };
  ParsedFilesMap::accessor acc;
  bool isNew = s_files.insert(acc, n);
  PhpFileWrapper* old = acc->second;
  SCOPE_EXIT {
    // run this just before acc is released
    if (old && old != acc->second) {
      if (old->getPhpFile() != acc->second->getPhpFile()) {
        toKill = old->getPhpFile();
      }
      delete old;
    }
    if (!acc->second) s_files.erase(acc);
  };

  assert(isNew || old); // We don't leave null entries around.
  bool isChanged = !isNew && old->isChanged(s);

  if (isNew || isChanged) {
    if (isPlainFile && !readFile(n, s, fileInfo)) {
      TRACE(1, "File disappeared between stat and FR::readNewFile: %s\n",
            rname->data());
      return nullptr;
    }
    ret = fileInfo.m_phpFile;
    if (isChanged && ret == old->getPhpFile()) {
      // The file changed but had the same contents.
      if (debug && md5Enabled()) {
        ReadLock lock(s_md5Lock);
        assert(s_md5Files.find(ret->getMd5())->second == ret);
      }
      return ret;
    }
  } else if (!isNew) {
    // Somebody might have loaded the file between when we dropped
    // our read lock and got the write lock
    ret = old->getPhpFile();
    return ret;
  }

  // If we get here the file was not in s_files or has changed on disk
  if (!ret) {
    // Try to read Unit from .hhbc repo.
    ret = readHhbc(n->data(), fileInfo);
  }
  if (!ret) {
    if (isAuthoritativeRepo()) {
      raise_error("Tried to parse %s in repo authoritative mode", n->data());
    }
    ret = parseFile(n->data(), fileInfo);
    if (!ret) return nullptr;
  }
  assert(ret != nullptr);

  if (isNew) {
    acc->second = new PhpFileWrapper(s, ret);
    ret->incRef();
    ret->setId(Transl::TargetCache::allocBit());
  } else {
    PhpFile *f = old->getPhpFile();
    if (f != ret) {
      ret->setId(f->getId());
      ret->incRef();
    }
    acc->second = new PhpFileWrapper(s, ret);
  }

  if (md5Enabled()) {
    WriteLock lock(s_md5Lock);
    s_md5Files[ret->getMd5()] = ret;
  }
  return ret;
}
Ejemplo n.º 25
0
int CDfuPlusHelper::despray()
{
    const char* srcname = globals->queryProp("srcname");
    if(srcname == NULL)
        throw MakeStringException(-1, "srcname not specified");
    
    const char* dstxml = globals->queryProp("dstxml");
    const char* dstip = globals->queryProp("dstip");
    const char* dstfile = globals->queryProp("dstfile");

    bool nowait = globals->getPropBool("nowait", false);

    MemoryBuffer xmlbuf;
    if(dstxml == NULL)
    {
        if(dstfile == NULL)
            throw MakeStringException(-1, "dstfile not specified");
        if(dstip == NULL) {
#ifdef DAFILESRV_LOCAL
            progress("dstip not specified - assuming spray from local machine\n");
            dstip = ".";
#else
            throw MakeStringException(-1, "dstip not specified");
#endif
        }
    }
    else
    {
        if(dstip != NULL || dstfile != NULL)
            throw MakeStringException(-1, "dstip/dstfile and dstxml can't be used at the same time");
        StringBuffer buf;
        buf.loadFile(dstxml);
        int len = buf.length();
        xmlbuf.setBuffer(len, buf.detach(), true);
    }

    if(dstxml == NULL)
        info("\nDespraying %s to host %s file %s\n", srcname, dstip, dstfile);
    else
        info("\nDespraying %s\n", srcname);

    Owned<IClientDespray> req = sprayclient->createDesprayRequest();
    req->setSourceLogicalName(srcname);
    if(dstxml == NULL)
    {
        req->setDestIP(dstip);
        req->setDestPath(dstfile);
    }
    else
        req->setDstxml(xmlbuf);

    req->setOverwrite(globals->getPropBool("overwrite", false));
    if(globals->hasProp("connect"))
        req->setMaxConnections(globals->getPropInt("connect"));
    if(globals->hasProp("throttle"))
        req->setThrottle(globals->getPropInt("throttle"));
    if(globals->hasProp("transferbuffersize"))
        req->setTransferBufferSize(globals->getPropInt("transferbuffersize"));

    if(globals->hasProp("norecover"))
        req->setNorecover(globals->getPropBool("norecover", false));
    else if(globals->hasProp("noRecover"))
        req->setNorecover(globals->getPropBool("noRecover", false));

    if(globals->hasProp("splitprefix"))
        req->setSplitprefix(globals->queryProp("splitprefix"));
    else if(globals->hasProp("splitPrefix"))
        req->setSplitprefix(globals->queryProp("splitPrefix"));

    if(globals->hasProp("wrap"))
        req->setWrap(globals->getPropBool("wrap", false));
    if(globals->hasProp("multicopy"))
        req->setMultiCopy(globals->getPropBool("multicopy", false));
    else if(globals->hasProp("multiCopy"))
        req->setMultiCopy(globals->getPropBool("multiCopy", false));

    if(globals->hasProp("compress"))
        req->setCompress(globals->getPropBool("compress", false));
    if(globals->hasProp("encrypt"))
        req->setEncrypt(globals->queryProp("encrypt"));
    if(globals->hasProp("decrypt"))
        req->setDecrypt(globals->queryProp("decrypt"));


    SocketEndpoint localep;
    StringBuffer localeps;
    if (checkLocalDaFileSvr(dstip,localep))
        dstip = localep.getUrlStr(localeps).str();
    Owned<IClientDesprayResponse> result = sprayclient->Despray(req);
    const char* wuid = result->getWuid();
    if(wuid == NULL || *wuid == '\0')
        exc(result->getExceptions(),"despraying");
    else
    {
        const char* jobname = globals->queryProp("jobname");
        if(jobname && *jobname)
            updatejobname(wuid, jobname);

        info("Submitted WUID %s\n", wuid);
        if(!nowait)
            waitToFinish(wuid);
    }

    return 0;
}
Ejemplo n.º 26
0
String highlight_php(CStrRef source, int line /* = 0 */,
                     int lineFocus0 /* = 0 */, int charFocus0 /* = 0 */,
                     int lineFocus1 /* = 0 */, int charFocus1 /* = 0 */) {
  StringBuffer res;
  Scanner scanner(source.data(), source.size(),
                  Scanner::AllowShortTags | Scanner::ReturnAllTokens);
  ScannerToken tok1, tok2;
  std::vector<pair<int, string> > ahead_tokens;
  Location loc1, loc2;

  const char *colorComment = NULL, *endComment = NULL;
  get_color(T_COMMENT, 0, 0, colorComment, endComment);

  int prev = 0;
  int tokid = scanner.getNextToken(tok1, loc1);
  int next = 0;
  while (tokid) {
    // look ahead
    next = scanner.getNextToken(tok2, loc2);
    while (next == T_WHITESPACE ||
           next == T_COMMENT ||
           next == T_DOC_COMMENT) {

      string text = tok2.text();
      string hcolor = check_char_highlight(lineFocus0, charFocus0,
                                           lineFocus1, charFocus1, loc2);
      if (!hcolor.empty()) {
        text = hcolor + text + ANSI_COLOR_END;
      }

      ahead_tokens.push_back(pair<int, string>(next, text));
      next = scanner.getNextToken(tok2, loc2);
    }

    string hcolor = check_char_highlight(lineFocus0, charFocus0,
                                         lineFocus1, charFocus1, loc1);

    if (tokid < 256) {
      if (!hcolor.empty()) {
        res.append(hcolor);
        res.append((char)tokid);
        res.append(ANSI_COLOR_END);
      } else {
        res.append((char)tokid);
      }
    } else {
      const char *color = NULL, *end = NULL;
      get_color(tokid, prev, next, color, end);
      if (!hcolor.empty()) {
        color = hcolor.c_str();
        end = ANSI_COLOR_END;
      }

      const std::string &text = tok1.text();
      int offset = 0;
      if (text[0] == '$') {
        if (!hcolor.empty()) {
          res.append(hcolor);
          res.append('$');
          res.append(ANSI_COLOR_END);
        } else {
          res.append('$');
        }
        offset = 1;
      }
      append_line_no(res, text.c_str() + offset, line, color, end,
                     lineFocus0, charFocus0, lineFocus1, charFocus1);
    }

    if (!ahead_tokens.empty()) {
      for (unsigned int i = 0; i < ahead_tokens.size(); i++) {
        bool comment = ahead_tokens[i].first != T_WHITESPACE;
        append_line_no(res, ahead_tokens[i].second.c_str(), line,
                       comment ? colorComment : NULL,
                       comment ? endComment : NULL,
                       lineFocus0, charFocus0, lineFocus1, charFocus1);
      }
      ahead_tokens.clear();
    }

    if (!(tokid == T_WHITESPACE || tokid == T_COMMENT ||
          tokid == T_DOC_COMMENT)) {
      prev = tokid;
    }
    tok1 = tok2;
    loc1 = loc2;
    tokid = next;
  }

  append_line_no(res, NULL, line, NULL, NULL,
                 lineFocus0, charFocus0, lineFocus1, charFocus1);
  return res.detach();
}
Ejemplo n.º 27
0
String xdebug_xml_return_node(xdebug_xml_node* node) {
  StringBuffer out;
  xdebug_xml_return_node_impl(out, node);
  return out.detach();
}
Ejemplo n.º 28
0
String DateInterval::format(CStrRef format_spec) {
  StringBuffer s;
  for(int i = 0; i < format_spec.length(); i++) {
    const int MAXLEN = 22; // 64bit signed int string length, plus terminating \0
    char buf[MAXLEN];
    int l;
    char c = format_spec.charAt(i);

    if (c != '%') {
      s.append(c);
      continue;
    }
    i++;
    if (i == format_spec.length()) {
      // End of format, use literal % and finish
      s.append(c);
      break;
    }
    c = format_spec.charAt(i);

    switch(c) {
      case 'Y': l = snprintf(buf, MAXLEN, "%02lld", getYears()); break;
      case 'y': l = snprintf(buf, MAXLEN, "%lld",   getYears()); break;

      case 'M': l = snprintf(buf, MAXLEN, "%02lld", getMonths()); break;
      case 'm': l = snprintf(buf, MAXLEN, "%lld",   getMonths()); break;

      case 'D': l = snprintf(buf, MAXLEN, "%02lld", getDays()); break;
      case 'd': l = snprintf(buf, MAXLEN, "%lld",   getDays()); break;

      case 'H': l = snprintf(buf, MAXLEN, "%02lld", getHours()); break;
      case 'h': l = snprintf(buf, MAXLEN, "%lld",   getHours()); break;

      case 'I': l = snprintf(buf, MAXLEN, "%02lld", getMinutes()); break;
      case 'i': l = snprintf(buf, MAXLEN, "%lld",   getMinutes()); break;

      case 'S': l = snprintf(buf, MAXLEN, "%02lld", getSeconds()); break;
      case 's': l = snprintf(buf, MAXLEN, "%lld",   getSeconds()); break;

      case 'a':
        if (haveTotalDays()) {
          l = snprintf(buf, MAXLEN, "%lld", getTotalDays());
        } else {
          l = snprintf(buf, MAXLEN, "(unknown)");
        }
        break;

      case 'R':
        l = snprintf(buf, MAXLEN, "%c", isInverted() ? '-' : '+'); break;
      case 'r':
        l = snprintf(buf, MAXLEN, "%s", isInverted() ? "-" : "");  break;

      case '%':
      default:
        l = 0;
        s.append('%');
        break;
    }

    if (l > 0) {
      s.append(buf, l);
    }
  }
  return s.detach();
}
Ejemplo n.º 29
0
String highlight_php(CStrRef source, int line) {
  Lock lock(Eval::Parser::s_lock);

  const char *input = source.data();
  istringstream iss(input);
  StringBuffer res;

  Eval::Scanner scanner(new ylmm::basic_buffer(iss, false, true),
                        true, false, true);
  Eval::Token tok1, tok2;
  std::vector<pair<int, Eval::Token> > ahead_tokens;
  ylmm::basic_location loc;

  const char *colorComment = NULL, *endComment = NULL;
  get_color(365 /* T_COMMENT */, 0, 0, colorComment, endComment);

  int prev = 0;
  int tokid = scanner.getNextToken(tok1, loc);
  int next = 0;
  while (tokid) {
    // look ahead
    next = scanner.getNextToken(tok2, loc);
    while (next == 370 /* T_WHITESPACE */ ||
           next == 365 /* T_COMMENT */ ||
           next == 366 /* T_DOC_COMMENT */) {
      ahead_tokens.push_back(pair<int, Eval::Token>(next, tok2));
      next = scanner.getNextToken(tok2, loc);
    }

    if (tokid < 256) {
      res.append((char)tokid);
    } else {
      const char *color = NULL, *end = NULL;
      get_color(tokid, prev, next, color, end);

      const std::string &text = tok1.getText();
      int offset = 0;
      if (text[0] == '$') {
        res.append('$');
        offset = 1;
      }
      append_line_no(res, text.c_str() + offset, line, color, end);
    }

    if (!ahead_tokens.empty()) {
      for (unsigned int i = 0; i < ahead_tokens.size(); i++) {
        bool comment = ahead_tokens[i].first != 370 /* T_WHITESPACE */;
        append_line_no(res, ahead_tokens[i].second.getText().c_str(), line,
                       comment ? colorComment : NULL,
                       comment ? endComment : NULL);
      }
      ahead_tokens.clear();
    }

    if (!(tokid == 370 /* T_WHITESPACE */ ||
          tokid == 365 /* T_COMMENT */ ||
          tokid == 366 /* T_DOC_COMMENT */)) {
      prev = tokid;
    }
    tok1 = tok2;
    tokid = next;
  }

  append_line_no(res, NULL, line, NULL, NULL);
  return res.detach();
}
Ejemplo n.º 30
0
Variant f_icu_match(CStrRef pattern, CStrRef subject,
                    VRefParam matches /* = null */, int64_t flags /* = 0 */) {
  UErrorCode status = U_ZERO_ERROR;

  if (matches.isReferenced()) {
    matches = Array();
  }

  // Create hash map key by concatenating pattern and flags.
  StringBuffer bpattern;
  bpattern.append(pattern);
  bpattern.append(':');
  bpattern.append(flags);
  String spattern = bpattern.detach();

  // Find compiled pattern matcher in hash map or add it.
  PatternStringMap::accessor accessor;
  const RegexPattern* rpattern;
  if (s_patternCacheMap.find(accessor, spattern.get())) {
    rpattern = accessor->second;
  } else {
    // First 32 bits are reserved for ICU-specific flags.
    rpattern = RegexPattern::compile(
      UnicodeString::fromUTF8(pattern.data()), (flags & 0xFFFFFFFF), status);
    if (U_FAILURE(status)) {
      return false;
    }

    if (s_patternCacheMap.insert(
      accessor, StringData::GetStaticString(spattern.get()))) {
      accessor->second = rpattern;
    } else {
      delete rpattern;
      rpattern = accessor->second;
    }
  }

  // Build regex matcher from compiled pattern and passed-in subject.
  UnicodeString usubject = UnicodeString::fromUTF8(subject.data());
  boost::scoped_ptr<RegexMatcher> matcher(rpattern->matcher(usubject, status));
  if (U_FAILURE(status)) {
    return false;
  }

  // Return 0 or 1 depending on whether or not a match was found and
  // (optionally), set matched (sub-)patterns for passed-in reference.
  int matched = 0;
  if (matcher->find()) {
    matched = 1;

    if (matches.isReferenced()) {
      int32_t count = matcher->groupCount();

      for (int32_t i = 0; i <= count; i++) {
        UnicodeString ustring = matcher->group(i, status);
        if (U_FAILURE(status)) {
          return false;
        }

        // Convert UnicodeString back to UTF-8.
        std::string string;
        ustring.toUTF8String(string);
        String match = String(string);

        if (flags & k_UREGEX_OFFSET_CAPTURE) {
          // start() returns the index in UnicodeString, which
          // normally means the index into an array of 16-bit
          // code "units" (not "points").
          int32_t start = matcher->start(i, status);
          if (U_FAILURE(status)) {
            return false;
          }

          start = usubject.countChar32(0, start);
          matches->append(CREATE_VECTOR2(match, start));
        } else {
          matches->append(match);
        }
      }
    }
  }

  return matched;
}