예제 #1
0
  /**
   * A synchronized call to {@link DartCompiler#compileLib(LibrarySource, CompilerConfiguration,
   * DartArtifactProvider, DartCompilerListener)}
   */
  public static void secureCompileLib(
      LibrarySource libSource,
      CompilerConfiguration config,
      DartArtifactProvider provider,
      DartCompilerListener listener)
      throws IOException {

    long start = System.currentTimeMillis();

    if (!DartSdkManager.getManager().hasSdk()) {
      return;
    }

    List<LibrarySource> embeddedLibraries = new ArrayList<LibrarySource>();
    // All calls to DartC must be synchronized
    synchronized (compilerLock) {
      DartCompiler.compileLib(libSource, embeddedLibraries, config, provider, listener);
    }

    long elapsed = System.currentTimeMillis() - start;
    Instrumentation.metric("DartCompilerUtils-secureCompileLib", elapsed).log();

    Instrumentation.operation("DartCompilerUtils-secureCompileLib", elapsed)
        .with("librarySource.Name", libSource.getName())
        .log();
  }
예제 #2
0
 /**
  * Return the file containing the initial state of the index. This file should be considered to be
  * read-only and should be loaded only if the normal index file does not yet exist. The initial
  * state of the index includes all of the information from the bundled libraries, but does not
  * include any information from loaded libraries.
  *
  * @return the file containing the initial state of the index
  */
 private File getInitialIndexFile() {
   // DartCore.getPlugin().getBundle().getResource(INITIAL_INDEX_FILE).openStream();
   // return new File(DartCore.getPlugin().getStateLocation().toFile(), INITIAL_INDEX_FILE);
   DartSdkManager sdkManager = DartSdkManager.getManager();
   if (sdkManager.hasSdk()) {
     return sdkManager.getSdk().getLibraryIndexFile();
   }
   return null;
 }
  @Override
  protected IStatus run(IProgressMonitor monitor) {
    IStatus status = DartSdkManager.getManager().upgrade(monitor);

    if (!status.isOK()) {
      if (status.getException() != null) {
        DartCore.logError(status.getException());
      }
    }

    return status;
  }
예제 #4
0
  private List<String> buildPubServeCommand() {
    DartSdk sdk = DartSdkManager.getManager().getSdk();
    File pubFile = sdk.getPubExecutable();
    List<String> args = new ArrayList<String>();
    args.add(pubFile.getAbsolutePath());
    args.add(SERVE_COMMAND);
    args.add("--port");
    args.add(PORT_NUMBER);
    args.add("--hostname");
    args.add(LOCAL_HOST_ADDR);

    return args;
  }
예제 #5
0
  /**
   * Runs the pub command.
   *
   * @return the result of running the pub command
   */
  public IStatus runSilent(IProgressMonitor monitor) {
    try {
      // Build the process description to run pub
      DartSdk sdk = DartSdkManager.getManager().getSdk();
      File pubFile = sdk.getPubExecutable();

      ProcessBuilder builder = new ProcessBuilder();
      builder.directory(container.getLocation().toFile());
      builder.redirectErrorStream(true);

      List<String> args = new ArrayList<String>();
      if (DartCore.isMac()) {
        args.add("/bin/bash");
        args.add("--login");
        args.add("-c");
        args.add("\"" + pubFile.getAbsolutePath() + "\"" + " " + command);
      } else {
        args.add(pubFile.getAbsolutePath());
        args.add(command);
      }
      builder.command(args);

      // Run the pub command as an external process.
      ProcessRunner runner = newProcessRunner(builder);

      try {
        runner.runSync(monitor);
      } catch (IOException e) {
        String message = NLS.bind(PubMessages.RunPubJob_failed, command, e.toString());
        return new Status(IStatus.CANCEL, DartCore.PLUGIN_ID, message, e);
      }

      StringBuilder stringBuilder = new StringBuilder();

      if (!runner.getStdOut().isEmpty()) {
        stringBuilder.append(runner.getStdOut().trim() + "\n"); // $NON-NLS-1$
      }

      int exitCode = runner.getExitCode();

      if (exitCode != 0) {
        String output = "[" + exitCode + "] " + stringBuilder.toString();
        String message = NLS.bind(PubMessages.RunPubJob_failed, command, output);
        return new Status(IStatus.ERROR, DartCore.PLUGIN_ID, message);
      }

      try {
        // Refresh the Eclipse resources
        container.refreshLocal(IResource.DEPTH_INFINITE, monitor);
      } catch (CoreException e) {
        // Log the exception and move on
        DartCore.logError("Exception refreshing " + container, e);
      }

      return new Status(IStatus.OK, DartCore.PLUGIN_ID, stringBuilder.toString());
    } catch (OperationCanceledException exception) {
      String message = NLS.bind(PubMessages.RunPubJob_canceled, command);
      return new Status(IStatus.CANCEL, DartCore.PLUGIN_ID, message, exception);
    } finally {
      monitor.done();
    }
  }
예제 #6
0
  /**
   * @param launchConfig
   * @param url
   * @param monitor
   * @param enableDebugging
   * @param browserLocation
   * @param browserName
   * @throws CoreException
   */
  private ListeningStream startNewBrowserProcess(
      DartLaunchConfigWrapper launchConfig,
      String url,
      IProgressMonitor monitor,
      boolean enableDebugging,
      IPath browserLocation,
      String browserName,
      StringBuilder argDescription)
      throws CoreException {

    Process process = null;
    monitor.worked(1);

    ProcessBuilder builder = new ProcessBuilder();
    Map<String, String> env = builder.environment();
    // Due to differences in 32bit and 64 bit environments, dartium 32bit launch does not work on
    // linux with this property.
    env.remove("LD_LIBRARY_PATH");

    // Add the environment variable DART_FLAGS="--enable-checked-mode"
    // to enable asserts and type checks
    if (launchConfig.getCheckedMode()) {
      env.put("DART_FLAGS", "--enable-checked-mode");
    }

    // Pass in --package-root if the preference is set
    String packageRoot = DartCore.getPlugin().getPackageRootPref();
    // TODO(keertip): if using default "packages" directory, do not set env variable
    // TODO(devoncarew): why are we only passing package root in when launching a file (not a url)?
    if (packageRoot != null && launchConfig.getShouldLaunchFile()) {
      try {
        String packageRootUri = getResourceServer().getUrlForFile(new Path(packageRoot).toFile());

        // Strip a trailing slash off the uri if the user setting didn't have one.
        if (!packageRoot.endsWith("/") && packageRootUri.endsWith("/")) {
          packageRootUri = packageRootUri.substring(0, packageRootUri.length() - 1);
        }

        env.put("DART_PACKAGE_ROOT", packageRootUri);
      } catch (IOException e) {
        DartDebugCorePlugin.logError(e);
      }
    }

    // This flag allows us to retrieve the dart: core sources from Dartium.
    env.put("DART_DEBUG_LIBS", "true");

    devToolsPortNumber = DEVTOOLS_PORT_NUMBER;

    if (enableDebugging) {
      devToolsPortNumber = NetUtils.findUnusedPort(DEVTOOLS_PORT_NUMBER);

      if (devToolsPortNumber == -1) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                DartDebugCorePlugin.PLUGIN_ID,
                "Unable to locate an available port for the Dartium debugger"));
      }
    }

    List<String> arguments =
        buildArgumentsList(launchConfig, browserLocation, url, enableDebugging, devToolsPortNumber);
    builder.command(arguments);
    builder.directory(DartSdkManager.getManager().getSdk().getDartiumWorkingDirectory());
    builder.redirectErrorStream(true);

    describe(arguments, argDescription);

    try {
      process = builder.start();
    } catch (IOException e) {
      DartDebugCorePlugin.logError("Exception while starting Dartium", e);

      throw new CoreException(
          new Status(
              IStatus.ERROR,
              DartDebugCorePlugin.PLUGIN_ID,
              "Could not launch browser: " + e.toString()));
    }

    browserProcess = process;

    return readFromProcessPipes(browserName, browserProcess.getInputStream());
  }
예제 #7
0
  protected void launchBrowser(
      ILaunch launch,
      DartLaunchConfigWrapper launchConfig,
      IFile file,
      String url,
      IProgressMonitor monitor,
      boolean enableDebugging)
      throws CoreException {

    // For now, we always start a debugging connection, even when we're not really debugging.
    boolean enableBreakpoints = enableDebugging;

    monitor.beginTask("Launching Dartium...", enableDebugging ? 7 : 2);

    File dartium = DartSdkManager.getManager().getSdk().getDartiumExecutable();

    if (dartium == null) {
      throw new CoreException(
          new Status(IStatus.ERROR, DartDebugCorePlugin.PLUGIN_ID, "Could not find Dartium"));
    }

    IPath browserLocation = new Path(dartium.getAbsolutePath());

    String browserName = dartium.getName();

    // avg: 0.434 sec (old: 0.597)
    LogTimer timer = new LogTimer("Dartium debug startup");

    // avg: 55ms
    timer.startTask(browserName + " startup");

    url = resolveLaunchUrl(file, url);

    // for now, check if browser is open, and connection is alive
    boolean restart =
        browserProcess == null
            || isProcessTerminated(browserProcess)
            || DartiumDebugTarget.getActiveTarget() == null
            || !DartiumDebugTarget.getActiveTarget().canTerminate();

    if (!restart) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);

      try {
        DartiumDebugTarget.getActiveTarget().navigateToUrl(url, enableBreakpoints);
      } catch (IOException e) {
        DartDebugCorePlugin.logError(e);
      }
    } else {
      terminateExistingBrowserProcess();

      StringBuilder processDescription = new StringBuilder();

      ListeningStream dartiumOutput =
          startNewBrowserProcess(
              launchConfig,
              url,
              monitor,
              enableDebugging,
              browserLocation,
              browserName,
              processDescription);

      sleep(100);

      monitor.worked(1);

      if (isProcessTerminated(browserProcess)) {
        DartDebugCorePlugin.logError("Dartium output: " + dartiumOutput.toString());

        throw new CoreException(
            new Status(
                IStatus.ERROR,
                DartDebugCorePlugin.PLUGIN_ID,
                "Could not launch browser - process terminated on startup"
                    + getProcessStreamMessage(dartiumOutput.toString())));
      }

      connectToChromiumDebug(
          dartium,
          browserName,
          launch,
          launchConfig,
          url,
          monitor,
          browserProcess,
          timer,
          enableBreakpoints,
          devToolsPortNumber,
          dartiumOutput,
          processDescription.toString());
    }

    DebugUIHelper.getHelper().activateApplication(dartium, "Chromium");

    timer.stopTask();
    timer.stopTimer();
    monitor.done();
  }
예제 #8
0
  /** A synchronized call to {@link DartCompiler#analyzeLibrary} */
  public static LibraryUnit secureAnalyzeLibrary(
      LibrarySource librarySource,
      final Map<URI, DartUnit> parsedUnits,
      final CompilerConfiguration config,
      DartArtifactProvider provider,
      DartCompilerListener listener)
      throws IOException {

    long start = System.currentTimeMillis();

    if (!DartSdkManager.getManager().hasSdk()) {
      return null;
    }

    final PackageLibraryManager manager = PackageLibraryManagerProvider.getPackageLibraryManager();
    AnalysisServer server = PackageLibraryManagerProvider.getDefaultAnalysisServer();

    URI librarySourceUri = librarySource.getUri();

    if (parsedUnits == null && !(librarySource instanceof LibraryWithSuppliedSources)) {

      // Resolve dart:<libname> to file URI before calling AnalysisServer
      URI libraryFileUri = manager.resolveDartUri(librarySourceUri);
      File libraryFile = new File(libraryFileUri.getPath());

      LibraryUnit ret = server.getSavedContext().resolve(libraryFile, 30000);

      long elapsed = System.currentTimeMillis() - start;
      Instrumentation.metric("DartCompilerUtils-secureAnalyzeLibrary", elapsed).log();
      Instrumentation.operation("DartCompilerUtils-secureAnalyzeLibrary", elapsed)
          .with("librarySource.Name", librarySource.getName())
          .with("librarySource.LastModified", librarySource.getLastModified())
          .log();

      return ret;
    }

    // Resolve the specified library against all currently cached libraries
    final Map<URI, LibraryUnit> resolvedLibs = server.getSavedContext().getResolvedLibraries(50);
    resolvedLibs.remove(librarySourceUri);

    // Construct the selective cache
    SelectiveCache selectiveCache =
        new DartCompiler.SelectiveCache() {
          @Override
          public Map<URI, LibraryUnit> getResolvedLibraries() {
            return resolvedLibs;
          }

          @Override
          public DartUnit getUnresolvedDartUnit(DartSource dartSrc) {
            if (parsedUnits == null) {
              return null;
            }
            URI srcUri = dartSrc.getUri();
            DartUnit parsedUnit = parsedUnits.remove(srcUri);
            if (parsedUnit != null) {
              return parsedUnit;
            }
            URI fileUri = manager.resolveDartUri(srcUri);
            return parsedUnits.remove(fileUri);
          }
        };

    Map<URI, LibraryUnit> libMap;
    // All calls to DartC must be synchronized
    synchronized (compilerLock) {
      libMap =
          DartCompiler.analyzeLibraries(
              librarySource, selectiveCache, config, provider, listener, false);
    }

    long elapsed = System.currentTimeMillis() - start;
    Instrumentation.metric("DartCompilerUtils-secureAnalyzeLibrary", elapsed)
        .with("libMapHasResult", Boolean.toString(libMap != null))
        .log();

    Instrumentation.operation("DartCompilerUtils-secureAnalyzeLibrary", elapsed)
        .with("librarySource.Name", librarySource.getName())
        .with("libMapHasResult", Boolean.toString(libMap != null))
        .with("librarySource.LastModified", librarySource.getLastModified())
        .log();

    return libMap != null ? libMap.get(librarySourceUri) : null;
  }
예제 #9
0
 /**
  * Write the current index to the SDK directory.
  *
  * @see DartSdk#getLibraryIndexFile()
  */
 public void writeIndexToSdk() {
   writeIndexTo(DartSdkManager.getManager().getSdk().getLibraryIndexFile());
 }
예제 #10
0
 public static boolean isAvailable() {
   return DartSdkManager.getManager().getSdk().getDartFmtExecutable().canExecute();
 }
예제 #11
0
  /**
   * Run the formatter on the given input source.
   *
   * @param source the source to pass to the formatter
   * @param selection the selection info to pass into the formatter
   * @param monitor the monitor for displaying progress
   * @throws IOException if an exception was thrown during execution
   * @throws CoreException if an exception occurs in file refresh
   * @return the formatted source (or null in case formatting could not be executed)
   */
  public static FormattedSource format(
      final String source, final Point selection, IProgressMonitor monitor)
      throws IOException, CoreException {

    File dartfmt = DartSdkManager.getManager().getSdk().getDartFmtExecutable();
    if (!dartfmt.canExecute()) {
      return null;
    }

    if (source.length() == 0) {
      FormattedSource result = new FormattedSource();
      result.source = source;
      return result;
    }

    ProcessBuilder builder = new ProcessBuilder();

    List<String> args = new ArrayList<String>();
    args.add(dartfmt.getPath());
    if (selection != null) {
      args.add(ARGS_SOURCE_FLAG + " " + selection.x + "," + selection.y);
    }
    args.add(ARGS_MAX_LINE_LEN_FLAG);
    if (getMaxLineLengthEnabled() && getMaxLineLength().length() > 0) {
      args.add(getMaxLineLength());
    } else {
      args.add("Infinity");
    }
    args.add(ARGS_INDENT_FLAG);
    args.add(getInsertSpacesForTabs() ? getSpacesPerIndent() : "tab");
    if (getPerformTransforms()) {
      args.add(ARGS_TRANSFORMS_FLAG);
    }
    args.add(ARGS_MACHINE_FORMAT_FLAG);

    builder.command(args);
    builder.redirectErrorStream(true);

    ProcessRunner runner =
        new ProcessRunner(builder) {
          @Override
          protected void processStarted(Process process) throws IOException {
            BufferedWriter writer =
                new BufferedWriter(
                    new OutputStreamWriter(process.getOutputStream(), "UTF-8"), source.length());
            writer.append(source);
            writer.close();
          }
        };

    runner.runSync(monitor);

    StringBuilder sb = new StringBuilder();

    if (!runner.getStdOut().isEmpty()) {
      sb.append(runner.getStdOut());
    }

    // TODO (pquitslund): better error handling
    if (runner.getExitCode() != 0) {
      sb.append(runner.getStdErr());
      throw new IOException(sb.toString());
    }

    String formattedSource = sb.toString();
    try {
      JSONObject json = new JSONObject(formattedSource);
      String sourceString = (String) json.get(JSON_SOURCE_KEY);
      JSONObject selectionJson = (JSONObject) json.get(JSON_SELECTION_KEY);
      // TODO (pquitslund): figure out why we (occasionally) need to remove an extra trailing
      // NEWLINE
      if (sourceString.endsWith("\n\n")) {
        sourceString = sourceString.substring(0, sourceString.length() - 1);
      }
      FormattedSource result = new FormattedSource();
      result.source = sourceString;
      result.selectionOffset = selectionJson.getInt(JSON_OFFSET_KEY);
      result.selectionLength = selectionJson.getInt(JSON_LENGTH_KEY);
      return result;
    } catch (JSONException e) {
      DartToolsPlugin.log(e);
      throw new IOException(e);
    }
  }