Version 1.21.0-dev.5.0
Merge 4ae06af529bcba94858c04537c00ec70fd6f6ec5 into dev
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a9e4b6f..32c3172 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,12 +15,32 @@
* `dart:developer`:
* The service protocol http server can now be controlled from Dart code.
+### Tool changes
+
+* Dart Dev Compiler
+
+ * Support calls to `loadLibrary()` on deferred libraries. Deferred libraries
+ are still loaded eagerly. (#27343)
+
## 1.20.1 - 2016-10-13
Patch release, resolves one issue:
* Dartium: Fixes a bug that caused crashes. No issue filed
+### Strong Mode
+
+* It is no longer a warning when casting from dynamic to a composite type
+ (SDK issue [27766](https://github.com/dart-lang/sdk/issues/27766)).
+
+ ```dart
+ main() {
+ dynamic obj = <int>[1, 2, 3];
+ // This is now allowed without a warning.
+ List<int> list = obj;
+ }
+ ```
+
## 1.20.0 - 2016-10-11
### Dart VM
diff --git a/DEPS b/DEPS
index 3bfa76e..32fb239 100644
--- a/DEPS
+++ b/DEPS
@@ -556,6 +556,20 @@
],
},
{
+ # Pull Debian wheezy sysroot for i386 Linux
+ 'name': 'sysroot_i386',
+ 'pattern': '.',
+ 'action': ['python', 'sdk/build/linux/sysroot_scripts/install-sysroot.py',
+ '--running-as-hook', '--arch', 'i386'],
+ },
+ {
+ # Pull Debian wheezy sysroot for amd64 Linux
+ 'name': 'sysroot_amd64',
+ 'pattern': '.',
+ 'action': ['python', 'sdk/build/linux/sysroot_scripts/install-sysroot.py',
+ '--running-as-hook', '--arch', 'amd64'],
+ },
+ {
# Pull clang if needed or requested via GYP_DEFINES.
'name': 'gn_clang',
'pattern': '.',
diff --git a/build/.gitignore b/build/.gitignore
index 6e337fe..56c0181 100644
--- a/build/.gitignore
+++ b/build/.gitignore
@@ -1,2 +1,6 @@
# Generated file containing information about the VS toolchain on Windows
win_toolchain.json
+
+# Pulled Debian wheezy sysroots
+linux/debian_wheezy_amd64-sysroot
+linux/debian_wheezy_i386-sysroot
diff --git a/build/config/linux/BUILD.gn b/build/config/linux/BUILD.gn
index 4b02a25..051809a 100644
--- a/build/config/linux/BUILD.gn
+++ b/build/config/linux/BUILD.gn
@@ -17,5 +17,14 @@
sysroot,
],
"value") ]
+
+ # When using the pulled wheezy sysroot with gcc, we have to specify these
+ # excplicitly.
+ if (dart_use_wheezy_sysroot && !is_clang) {
+ cflags += [
+ "-I=/usr/include/c++/4.6",
+ "-I=/usr/include/c++/4.6/i486-linux-gnu",
+ ]
+ }
}
}
diff --git a/build/config/sysroot.gni b/build/config/sysroot.gni
index 37faae0..bb29e6c 100644
--- a/build/config/sysroot.gni
+++ b/build/config/sysroot.gni
@@ -9,6 +9,20 @@
# The absolute path of the sysroot that is applied when compiling using
# the target toolchain.
target_sysroot = ""
+
+ # Whether the Debian wheezy sysroot should be used.
+ dart_use_wheezy_sysroot = false
+}
+
+if (is_linux && dart_use_wheezy_sysroot) {
+ if (current_cpu == "x86") {
+ target_sysroot = rebase_path("//build/linux/debian_wheezy_i386-sysroot")
+ } else if (current_cpu == "x64") {
+ target_sysroot = rebase_path("//build/linux/debian_wheezy_amd64-sysroot")
+ } else {
+ print("There is no Debian wheezy sysroot present for $current_cpu")
+ assert(false)
+ }
}
if (current_toolchain == default_toolchain && target_sysroot != "") {
diff --git a/build/detect_host_arch.py b/build/detect_host_arch.py
new file mode 100755
index 0000000..19579eb
--- /dev/null
+++ b/build/detect_host_arch.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+# Copyright 2014 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""Outputs host CPU architecture in format recognized by gyp."""
+
+import platform
+import re
+import sys
+
+
+def HostArch():
+ """Returns the host architecture with a predictable string."""
+ host_arch = platform.machine()
+
+ # Convert machine type to format recognized by gyp.
+ if re.match(r'i.86', host_arch) or host_arch == 'i86pc':
+ host_arch = 'ia32'
+ elif host_arch in ['x86_64', 'amd64']:
+ host_arch = 'x64'
+ elif host_arch.startswith('arm'):
+ host_arch = 'arm'
+
+ # platform.machine is based on running kernel. It's possible to use 64-bit
+ # kernel with 32-bit userland, e.g. to give linker slightly more memory.
+ # Distinguish between different userland bitness by querying
+ # the python binary.
+ if host_arch == 'x64' and platform.architecture()[0] == '32bit':
+ host_arch = 'ia32'
+
+ return host_arch
+
+def DoMain(_):
+ """Hook to be called from gyp without starting a separate python
+ interpreter."""
+ return HostArch()
+
+if __name__ == '__main__':
+ print DoMain([])
diff --git a/build/linux/sysroot_scripts/install-sysroot.py b/build/linux/sysroot_scripts/install-sysroot.py
index 99fc2d6..f305f26 100755
--- a/build/linux/sysroot_scripts/install-sysroot.py
+++ b/build/linux/sysroot_scripts/install-sysroot.py
@@ -108,18 +108,6 @@
print 'Unable to detect host architecture'
return 1
- if options.running_as_hook and target_arch != 'arm' and target_arch != 'mips':
- # When run from runhooks, only install the sysroot for an Official Chrome
- # Linux build, except on ARM where we always use a sysroot.
- skip_if_defined = ['branding=Chrome', 'buildtype=Official']
- skip_if_undefined = ['chromeos=1']
- for option in skip_if_defined:
- if option not in gyp_defines:
- return 0
- for option in skip_if_undefined:
- if option in gyp_defines:
- return 0
-
# The sysroot directory should match the one specified in build/common.gypi.
# TODO(thestig) Consider putting this else where to avoid having to recreate
# it on every build.
diff --git a/docs/language/dartLangSpec.tex b/docs/language/dartLangSpec.tex
index c3aa30a..5e009e6 100644
--- a/docs/language/dartLangSpec.tex
+++ b/docs/language/dartLangSpec.tex
@@ -38,7 +38,7 @@
A conforming implementation of the Dart programming language must provide and support all the APIs (libraries, types, functions, getters, setters, whether top-level, static, instance or local) mandated in this specification.
\LMHash{}
-A conforming implementation is permitted to provide additional APIs, but not additional syntax, except for experimental features in support of null-aware cascades and tear-offs that are likely to be introduced in the next revision of this specification.
+A conforming implementation is permitted to provide additional APIs, but not additional syntax, except for experimental features in support of null-aware cascades that are likely to be introduced in the next revision of this specification.
\section{Normative References}
\LMLabel{ecmaNormativeReferences}
@@ -2376,7 +2376,6 @@
literal;
identifier;
newExpression;
- \NEW{} type `\#' (`{\escapegrammar .}' identifier)?;
constObjectExpression;
`(' expression `)'
.
@@ -4030,17 +4029,13 @@
Property extraction can be either {\em conditional} or {\em unconditional}.
-\rationale {
-Tear-offs using the \cd{ x\#id} syntax cannot be conditional at this time; this is inconsistent, and is likely to be addressed in the near future, perhaps via notation such as \cd{ x?\#id} . As indicated in section \ref{ecmaConformance}, experimentation in this area is allowed.
-}
-
Evaluation of a {\em conditional property extraction expression} $e$ of the form $e_1?.id$ is equivalent to the evaluation of the expression $((x) => x == \NULL ? \NULL : x.id)(e_1)$.
unless $e_1$ is a type literal, in which case it is equivalent to $e_1.m$.
The static type of $e$ is the same as the static type of $e_1.id$. Let $T$ be the static type of $e_1$ and let $y$ be a fresh variable of type $T$. Exactly the same static warnings that would be caused by $y.id$ are also generated in the case of $e_1?.id$.
\LMHash{}
-Unconditional property extraction takes several syntactic forms: $e.m$ (\ref{getterAccessAndMethodExtraction}), $\SUPER.m$ (\ref{superGetterAccessAndMethodClosurization}), $e\#m$ (\ref{generalClosurization}), $\NEW{}$ $T\#m$ (\ref{namedConstructorExtraction}), $\NEW{}$ $T\#$ (\ref{anonymousConstructorExtraction}) and $\SUPER\#m$ (\ref{generalSuperPropertyExtraction}), where $e$ is an expression, $m$ is an identifier optionally followed by an equal sign and $T$ is a type.
+Unconditional property extraction has one of two syntactic forms: $e.m$ (\ref{getterAccessAndMethodExtraction}) or $\SUPER.m$ (\ref{superGetterAccessAndMethodClosurization}), where $e$ is an expression and $m$ is an identifier.
\subsubsection{Getter Access and Method Extraction}
\LMLabel{getterAccessAndMethodExtraction}
@@ -4143,145 +4138,17 @@
\end{itemize}
-\subsubsection{General Closurization}
-\LMLabel{generalClosurization}
-
-\LMHash{}
-Evaluation of a property extraction $i$ of the form $e\#m$ proceeds as follows:
-
-\LMHash{}
-First, the expression $e$ is evaluated to an object $o$. Then:
-
-\LMHash{}
- if $m$ is a setter name, let $f$ be the result of looking up setter $m$ in $o$ with respect to the current library $L$. If $o$ is an instance of \cd{Type} but $e$ is not a constant type literal, then if $f$ is a method that forwards to a static setter, setter lookup fails. If setter lookup succeeds then $i$ evaluates to the closurization of setter $f$ on object $o$ (\ref{ordinaryMemberClosurization}).
- If setter lookup failed, a \cd{NoSuchMethodError} is thrown.
-
- \rationale {
-It would be more in keeping with the rules of Dart to invoke \cd{noSuchMethod} in this and similar cases below. However, current implementations of \cd{noSuchMethod} cannot distinguish between an invocation of a closurization and an actual call. It is likely that future versions of Dart will provide a mechanism to detect whether \cd{noSuchMethod} is invoked in response to a closurization, say by means of a getter like \cd{isTearOff}. By being conservative at this stage and insisting on failure, we can ensure that no functioning code will break when/if this functionality is introduced.
- }
-
-
- \LMHash{}
-If $m$ is not a setter name, let $f$ be the result of looking up method $m$ in $o$ with respect to the current library $L$. If $o$ is an instance of \cd{Type} but $e$ is not a constant type literal, then if $f$ is a method that forwards to a static method, method lookup fails. If method lookup succeeds then $i$ evaluates to the closurization of method $f$ on object $o$ (\ref{ordinaryMemberClosurization}).
-
-\LMHash{}
-If method lookup failed, let $f$ be the result of looking up getter $m$ in $o$ with respect to the current library $L$. If $o$ is an instance of \cd{Type} but $e$ is not a constant type literal, then if $f$ is a method that forwards to a static getter, getter lookup fails. If getter lookup succeeds then $i$ evaluates to the closurization of getter $f$ on object $o$ (\ref{ordinaryMemberClosurization}).
- If getter lookup failed, a \cd{NoSuchMethodError} is thrown.
-
-
-
-
-%\LMHash{}
-%Otherwise, a new instance $im$ of the predefined class \code{Invocation} is created, such that :
-%\begin{itemize}
-%\item If $m$ is a setter name, \code{im.isSetter} evaluates to \code{\TRUE{}}; otherwise \code{im.isMethod} evaluates to \code{\TRUE{}}
-%\item \code{im.memberName} evaluates to the symbol \code{m}.
-%\item \code{im.positionalArguments} evaluates to the value of \code{\CONST{} []}.
-%\item \code{im.namedArguments} evaluates to the value of \code{\CONST{} \{\}}.
-%\end{itemize}
-%Then the method \code{noSuchMethod()} is looked up in $o$ and invoked with argument $im$, and the result of this invocation is the result of evaluating $i$. However, if the implementation found cannot be invoked with a single positional argument, the implementation of \code{noSuchMethod()} in class \code{Object} is invoked on $o$ with argument $im'$, where $im'$ is an instance of \code{Invocation} such that :
-%\begin{itemize}
-%\item \code{im'.isMethod} evaluates to \code{\TRUE{}}.
-%\item \code{im'.memberName} evaluates to \code{\#noSuchMethod}.
-%\item \code{im'.positionalArguments} evaluates to an immutable list whose sole element is $im$.
-%\item \code{im'.namedArguments} evaluates to the value of \code{\CONST{} \{\}}.
-%\end{itemize}
-%and the result of this latter invocation is the result of evaluating $i$.
-
-\LMHash{}
-It is a compile-time error if $e$ is a prefix object, $p$, (\ref{imports}) and $m$ refers to a type accessible via $p$ or to a member of class \cd{Object}.
-
-\commentary{
-This restriction is in line with other limitations on the use of prefixes as objects. The only permitted uses of $p\#m$ are closurizing top level methods and getters imported via the prefix $p$. Top level methods are directly available by their qualified names: $p.m$. However, getters and setters are not, and allowing their closurization is the whole point of the $e\#m$ syntax.
-}
-
-\LMHash{}
-Let $T$ be the static type of $e$. It is a static type warning if $T$ does not have an accessible instance method or getter named $m$ unless either:
-\begin{itemize}
-\item $T$ or a superinterface of $T$ is annotated with an annotation denoting a constant identical to the constant \code{@proxy} defined in \cd{dart:core}. Or
-\item $T$ is \cd{Type}, $e$ is a constant type literal and the class corresponding to $e$ declares an accessible static method or getter named $m$.
-\item $T$ is \code{Function} and $m$ is \CALL.
-\end{itemize}
-
-The static type of $i$ is:
-\begin{itemize}
-\item The static type of function $T.m$, if $T$ has an accessible instance member named $m$.
-\item The static type of function $T.m$, if $T$ is \cd{Type}, $e$ is a constant type literal and the class corresponding to $e$ declares an accessible static member or constructor named $m$.
-\item \code{Function} if $T$ is \code{Function} and $m$ is \CALL.
-\item The type \DYNAMIC{} otherwise.
-\end{itemize}
-
-\subsubsection{Named Constructor Extraction}
-\LMLabel{namedConstructorExtraction}
-
-\LMHash{}
-Evaluation of a property extraction $i$ of the form \NEW{} $T\#m$ proceeds as follows:
-
-\LMHash{}
-If $T$ is a malformed type (\ref{staticTypes}), a dynamic error occurs. If $T$ is a deferred type with prefix $p$, then if $p$ has not been successfully loaded, a dynamic error occurs. If $T$ does not denote a class, a dynamic error occurs. In checked mode, if $T$ or any of its superclasses is malbounded a dynamic error occurs. Otherwise, if the type $T$ does not declare an accessible named constructor $f$ with name $m$, a \cd{NoSuchMethodError} is thrown. Otherwise, $i$ evaluates to the closurization of constructor $f$ of type $T$ (\ref{namedConstructorClosurization}).
-
-\commentary{Note that if $T$ is malformed or malbounded, a static warning occurs, as always.}
-
-\LMHash{}
-The static type of $i$ is the type of the constructor function, if $T$ denotes a class in the surrounding scope with an accessible constructor $f$ named $m$. Otherwise the static type of $i$ is \DYNAMIC{}.
-
-It is a compile-time error if $T$ is an enumerated type (\ref{enums}).
-
-\subsubsection{Anonymous Constructor Extraction}
-\LMLabel{anonymousConstructorExtraction}
-
-\LMHash{}
-Evaluation of a property extraction $i$ of the form \NEW{} $T\#$ proceeds as follows:
-
-\LMHash{}
-If $T$ is a malformed type (\ref{staticTypes}), a dynamic error occurs. If $T$ is a deferred type with prefix $p$, then if $p$ has not been successfully loaded, a dynamic error occurs. If $T$ does not denote a class, a dynamic error occurs. In checked mode, if $T$ or any of its superclasses is malbounded a dynamic error occurs. Otherwise, if the type $T$ does not declare an accessible anonymous constructor, a \cd{NoSuchMethodError} is thrown. Otherwise, $i$ evaluates to the closurization of the anonymous constructor of type $T$ (\ref{anonymousConstructorClosurization}).
-
-\commentary{Again, note that if $T$ is malformed or malbounded, existing rules ensure that a static warning occurs. This also means that $x\#$ where $x$ is not a type will always give a static warning.}
-
-\LMHash{}
-The static type of $i$ is the type of the constructor function $T()$, if $T$ denotes a class in the surrounding scope with an anonymous constructor $T()$. Otherwise the static type of $i$ is \DYNAMIC{}.
-
-It is a compile-time error if $T$ is an enumerated type (\ref{enums}).
-
-
-\subsubsection{General Super Property Extraction}
-\LMLabel{generalSuperPropertyExtraction}
-
-
-\LMHash{}
-Evaluation of a property extraction $i$ of the form \SUPER$\#m$ proceeds as follows:
-
- \LMHash{}
-Let $g$ be the method currently executing, and let $C$ be the class in which $g$ was looked up. Let $S_{dynamic}$ be the superclass of $C$.
-
- \LMHash{}
-If $m$ is a setter name, let $f$ be the result of looking up setter $m$ in $S_{dynamic}$ with respect to the current library $L$. If setter lookup succeeds then $i$ evaluates to the closurization of setter $f$ with respect to superclass $S_{dynamic}$ (\ref{superClosurization}). If setter lookup failed, a \cd{NoSuchMethodError} is thrown.
-
-If $m$ is not a setter name, let $f$ be the result of looking up method $m$ in $S_{dynamic}$ with respect to the current library $L$. If method lookup succeeds then $i$ evaluates to the closurization of method $m$ with respect to superclass $S_{dynamic}$ (\ref{superClosurization}).
-
-\LMHash{}
- Otherwise, let $f$ be the result of looking up getter $m$ in $S_{dynamic}$ with respect to the current library $L$. If getter lookup succeeds then $i$ evaluates to the closurization of getter $f$ with respect to superclass $S_{dynamic}$ (\ref{superClosurization}). If getter lookup failed, a \cd{NoSuchMethodError} is thrown.
-
-\LMHash{}
-Let $S_{static}$ be the superclass of the immediately enclosing class.It is a static type warning if $S_{static}$ does not have an accessible instance member named $m$.
-
-\LMHash{}
-The static type of $i$ is the static type of the function $S_{static}.m$, if $S_{static}$ has an accessible instance member named $m$. Otherwise the static type of $i$ is \DYNAMIC{}.
-
-
-
\subsubsection{Ordinary Member Closurization}
\LMLabel{ordinaryMemberClosurization}
-
\LMHash{}
Let $o$ be an object, and let $u$ be a fresh final variable bound to $o$.
The {\em closurization of method $f$ on object $o$} is defined to be equivalent to:
\begin{itemize}
-\item $(a) \{\RETURN{}$ $u$ $op$ $a;$\} if $f$ is named $op$ and $op$ is one of \code{$<$, $>$, $<$=, $>$=, ==, -, +, /, \~{}/, *, \%, $|$, \^{}, \&, $<<$, $>>$} (this precludes closurization of unary -).
-\item $() \{\RETURN{}$ \~{} $u;$\} if $f$ is named \~{}.
-\item $(a) \{\RETURN{}$ $u[a];$\} if $f$ is named $[]$.
-\item $(a, b) \{\RETURN{}$ $u[a] = b;$\} if $f$ is named $[]=$.
+%\item $(a) \{\RETURN{}$ $u$ $op$ $a;$\} if $f$ is named $op$ and $op$ is one of \code{$<$, $>$, $<$=, $>$=, ==, -, +, /, \~{}/, *, \%, $|$, \^{}, \&, $<<$, $>>$} (this precludes closurization of unary -).
+%\item $() \{\RETURN{}$ \~{} $u;$\} if $f$ is named \~{}.
+%\item $(a) \{\RETURN{}$ $u[a];$\} if $f$ is named $[]$.
+%\item $(a, b) \{\RETURN{}$ $u[a] = b;$\} if $f$ is named $[]=$.
\item
\begin{dartCode}
$(r_1, \ldots, r_n, \{p_1 = d_1, \ldots , p_k = d_k\})$ \{
@@ -4295,20 +4162,13 @@
\RETURN{} $u.m(r_1, \ldots, r_n, p_1, \ldots, p_k)$;
\}
\end{dartCode}
-
if $f$ is named $m$ and has required parameters $r_1, \ldots, r_n$, and optional positional parameters $p_1, \ldots, p_k$ with defaults $d_1, \ldots, d_k$.
-\end{itemize}
+%\end{itemize}
\LMHash{}
-Except that iff \code{identical($o_1, o_2$)} then \cd{$o_1\#m$ == $o_2\#m$}, \cd{$o_1.m$ == $o_2.m$}, \cd{$o_1\#m$ == $o_2.m$} and \cd{$o_1.m$ == $o_2\#m$}.
+Except that iff \code{identical($o_1, o_2$)} then \cd{$o_1.m$ == $o_2.m$}.
%\item The static type of the property extraction is the static type of function $T.m$, where $T$ is the static type of $e$, if $T.m$ is defined. Otherwise the static type of $e.m$ is \DYNAMIC{}.
-\LMHash{}
-The {\em closurization of getter $f$ on object $o$} is defined to be equivalent to \cd{()\{\RETURN{} u.m;\}} if $f$ is named $m$, except that iff \code{identical($o_1, o_2$)} then \cd{$o_1\#m$ == $o_2\#m$}.
-
-\LMHash{}
-The {\em closurization of setter $f$ on object $o$} is defined to be equivalent to \cd{(a)\{\RETURN{} u.m = a;\}} if $f$ is named $m=$, except that iff \code{identical($o_1, o_2$)} then \cd{$o_1\#m=$ == $o_2\#m=$}.
-
\commentary{
There is no guarantee that \cd{identical($o_1.m, o_2.m$)}. Dart implementations are not required to canonicalize these or any other closures.
}
@@ -4318,73 +4178,6 @@
The special treatment of equality in this case facilitates the use of extracted property functions in APIs where callbacks such as event listeners must often be registered and later unregistered. A common example is the DOM API in web browsers.
}
-\commentary {
-Observations:
-
-One cannot closurize a constructor, getter or a setter via the dot based syntax. One must use the \# based form. One can tell whether one implemented a property via a method or via a field/getter, which means that one has to plan ahead as to what construct to use, and that choice is reflected in the interface of the class.
-}
-
-
-
-\subsubsection{Named Constructor Closurization}
-\LMLabel{namedConstructorClosurization}
-
-\LMHash{}
-The {\em closurization of constructor $f$ of type $T$} is defined to be equivalent to:
-\begin{itemize}
-\item
-\begin{dartCode}
-$(r_1, \ldots, r_n, \{p_1 = d_1, \ldots , p_k = d_k\})$ \{
- \RETURN{} \NEW{} $T.m(r_1, \ldots, r_n, p_1: p_1, \ldots, p_k: p_k);$
-\}
-\end{dartCode}
-
-if $f$ is a named constructor with name $m$ that has required parameters $r_1, \ldots, r_n$, and named parameters $p_1, \ldots, p_k$ with defaults $d_1, \ldots, d_k$.
-\item
-\begin{dartCode}
-$(r_1, \ldots, r_n, [p_1 = d_1, \ldots , p_k = d_k])$\{
- \RETURN{} \NEW{} $T.m(r_1, \ldots, r_n, p_1, \ldots, p_k)$;
-\}
-\end{dartCode}
-
-if $f$ is a named constructor with name $m$ that has required parameters $r_1, \ldots, r_n$, and optional positional parameters $p_1, \ldots, p_k$ with defaults $d_1, \ldots, d_k$.
-\end{itemize}
-
-\LMHash{}
-Except that iff \code{identical($T_1, T_2$)} then \cd{\NEW{} $T_1\#m$ == \NEW{} $T_2\#m$}.
-
-\commentary{
-The above implies that for non-parameterized types, one can rely on the equality of closures resulting from closurization on the ``same'' type. For parameterized types, one cannot, since there is no requirement to canonicalize them.
-}
-
-\subsubsection{Anonymous Constructor Closurization}
-\LMLabel{anonymousConstructorClosurization}
-
-\LMHash{}
-The {\em closurization of anonymous constructor $f$ of type $T$} is defined to be equivalent to:
-\begin{itemize}
-\item
-\begin{dartCode}
-$(r_1, \ldots, r_n, \{p_1 = d_1, \ldots , p_k = d_k\})$ \{
- \RETURN{} \NEW{} $T(r_1, \ldots, r_n, p_1: p_1, \ldots, p_k: p_k);$
-\}
-\end{dartCode}
-
-if $f$ is an anonymous constructor that has required parameters $r_1, \ldots, r_n$, and named parameters $p_1, \ldots, p_k$ with defaults $d_1, \ldots, d_k$.
-\item
-\begin{dartCode}
-$(r_1, \ldots, r_n, [p_1 = d_1, \ldots , p_k = d_k])$\{
- \RETURN{} \NEW{} $T(r_1, \ldots, r_n, p_1, \ldots, p_k)$;
-\}
-\end{dartCode}
-
-if $f$ is an anonymous constructor that has required parameters $r_1, \ldots, r_n$, and optional positional parameters $p_1, \ldots, p_k$ with defaults $d_1, \ldots, d_k$.
-\end{itemize}
-
-\LMHash{}
-Except that iff \code{identical($T_1, T_2$)} then \cd{\NEW{} $T_1\#$ == \NEW{} $T_2\#$}.
-
-
\subsubsection{Super Closurization}
\LMLabel{superClosurization}
@@ -4393,10 +4186,10 @@
\LMHash{}
\begin{itemize}
-\item $(a) \{\RETURN{}$ \SUPER{} $op$ $a;$\} if $f$ is named $op$ and $op$ is one of \code{$<$, $>$, $<$=, $>$=, ==, -, +, /, \~{}/, *, \%, $|$, \^{}, \&, $<<$, $>>$}.
-\item $() \{\RETURN{}$ \~{}\SUPER;\} if $f$ is named \~{}.
-\item $(a) \{\RETURN{}$ $\SUPER[a];$\} if $f$ is named $[]$.
-\item $(a, b) \{\RETURN{}$ $\SUPER[a] = b;$\} if $f$ is named $[]=$.
+%\item $(a) \{\RETURN{}$ \SUPER{} $op$ $a;$\} if $f$ is named $op$ and $op$ is one of \code{$<$, $>$, $<$=, $>$=, ==, -, +, /, \~{}/, *, \%, $|$, \^{}, \&, $<<$, $>>$}.
+%\item $() \{\RETURN{}$ \~{}\SUPER;\} if $f$ is named \~{}.
+%\item $(a) \{\RETURN{}$ $\SUPER[a];$\} if $f$ is named $[]$.
+%\item $(a, b) \{\RETURN{}$ $\SUPER[a] = b;$\} if $f$ is named $[]=$.
\item
\begin{dartCode}
$(r_1, \ldots, r_n, \{p_1 = d_1, \ldots , p_k = d_k\})$ \{
@@ -4410,20 +4203,11 @@
\RETURN{} \SUPER$.m(r_1, \ldots, r_n, p_1, \ldots, p_k)$;
\}
\end{dartCode}
-
if $f$ is named $m$ and has required parameters $r_1, \ldots, r_n$, and optional positional parameters $p_1, \ldots, p_k$ with defaults $d_1, \ldots, d_k$.
\end{itemize}
\LMHash{}
-Except that iff two closurizations were created by code declared in the same class with identical bindings of \THIS{} then \cd{\SUPER$_1\#m$ == \SUPER$_2\#m$}, \cd{\SUPER$_1.m$ == \SUPER$_2.m$}, \cd{\SUPER$_1\#m$ == \SUPER$_2.m$} and \cd{\SUPER$_1.m$ == \SUPER$_2\#m$}.
-
-
-\LMHash{}
-The {\em closurization of getter $f$ with respect to superclass $S$} is defined to be equivalent to \cd{()\{\RETURN{} \SUPER.m;\}} if $f$ is named $m$, except that iff two closurizations were created by code declared in the same class with identical bindings of \THIS{} then \cd{\SUPER$_1\#m$ == \SUPER$_2\#m$}.
-
-\LMHash{}
-The {\em closurization of setter $f$ with respect to superclass $S$} is defined to be equivalent to \cd{(a)\{\RETURN{} \SUPER.m = a;\}} if $f$ is named $m=$, except that iff two closurizations were created by code declared in the same class with identical bindings of \THIS{} then \cd{\SUPER$_1\#m=$ == \SUPER$_2\#m=$}.
-
+Except that iff two closurizations were created by code declared in the same class with identical bindings of \THIS{} then \cd{\SUPER$_1.m$ == \SUPER$_2.m$}.
\subsection{ Assignment}
@@ -5055,7 +4839,7 @@
\begin{grammar}
{\bf postfixExpression:}assignableExpression postfixOperator;
- primary (selector* $|$ ( `\#' ( (identifier `='?) $|$ operator)))
+ primary selector*
.
{\bf postfixOperator:}
@@ -5311,7 +5095,7 @@
%If no such member exists, let $d$ be the declaration of the static member name $id$ declared in a superclass of the current class, if it exists.
\begin{itemize}
-\item if $d$ is a prefix $p$, a compile-time error occurs unless the token immediately following $d$ is \code{'.'} or \code{'\#'}.
+\item if $d$ is a prefix $p$, a compile-time error occurs unless the token immediately following $d$ is \code{'.'}.
\item If $d$ is a class or type alias $T$, the value of $e$ is an instance of class \code{Type} (or a subclass thereof) reifying $T$.
\item If $d$ is a type parameter $T$, then the value of $e$ is the value of the actual type argument corresponding to $T$ that was passed to the generative constructor that created the current binding of \THIS{}. If, however, $e$ occurs inside a static member, a compile-time error occurs.
diff --git a/pkg/analysis_server/lib/src/analysis_server.dart b/pkg/analysis_server/lib/src/analysis_server.dart
index 46ea334..99f3724 100644
--- a/pkg/analysis_server/lib/src/analysis_server.dart
+++ b/pkg/analysis_server/lib/src/analysis_server.dart
@@ -16,8 +16,6 @@
import 'package:analysis_server/src/channel/channel.dart';
import 'package:analysis_server/src/computer/new_notifications.dart';
import 'package:analysis_server/src/context_manager.dart';
-import 'package:analysis_server/src/domains/analysis/navigation.dart';
-import 'package:analysis_server/src/domains/analysis/navigation_dart.dart';
import 'package:analysis_server/src/operation/operation.dart';
import 'package:analysis_server/src/operation/operation_analysis.dart';
import 'package:analysis_server/src/operation/operation_queue.dart';
@@ -322,6 +320,16 @@
ByteStore byteStore;
/**
+ * The set of the files that are currently priority.
+ */
+ final Set<String> priorityFiles = new Set<String>();
+
+ /**
+ * The cached results units for [priorityFiles].
+ */
+ final Map<String, nd.AnalysisResult> priorityFileResults = {};
+
+ /**
* Initialize a newly created server to receive requests from and send
* responses to the given [channel].
*
@@ -561,6 +569,33 @@
return null;
}
+ /**
+ * Return the analysis driver to which the file with the given [path] is
+ * added if exists, otherwise the first driver, otherwise `null`.
+ */
+ nd.AnalysisDriver getAnalysisDriver(String path) {
+ Iterable<nd.AnalysisDriver> drivers = driverMap.values;
+ if (drivers.isNotEmpty) {
+ return drivers.firstWhere((driver) => driver.isAddedFile(path),
+ orElse: () => drivers.first);
+ }
+ return null;
+ }
+
+ /**
+ * Return the analysis result for the file with the given [path]. The file is
+ * analyzed in one of the analysis drivers to which the file was added,
+ * otherwise in the first driver, otherwise `null` is returned.
+ */
+ Future<nd.AnalysisResult> getAnalysisResult(String path) async {
+ nd.AnalysisResult result = priorityFileResults[path];
+ if (result != null) {
+ return result;
+ }
+ nd.AnalysisDriver driver = getAnalysisDriver(path);
+ return driver?.getResult(path);
+ }
+
CompilationUnitElement getCompilationUnitElement(String file) {
ContextSourcePair pair = getContextSourcePair(file);
if (pair == null) {
@@ -1218,6 +1253,13 @@
*/
void setPriorityFiles(String requestId, List<String> files) {
if (options.enableNewAnalysisDriver) {
+ // Flush results for files that are not priority anymore.
+ priorityFiles
+ .difference(files.toSet())
+ .forEach(priorityFileResults.remove);
+ priorityFiles.clear();
+ priorityFiles.addAll(files);
+ // Set priority files in drivers.
driverMap.values.forEach((driver) {
driver.priorityFiles = files;
});
@@ -1344,6 +1386,8 @@
void updateContent(String id, Map<String, dynamic> changes) {
if (options.enableNewAnalysisDriver) {
changes.forEach((file, change) {
+ priorityFileResults.remove(file);
+
// Prepare the new contents.
String oldContents = fileContentOverlay[file];
String newContents;
@@ -1715,21 +1759,26 @@
// TODO(scheglov) send server status
});
analysisDriver.results.listen((result) {
- new_sendErrorNotification(analysisServer, result);
+ if (analysisServer.priorityFiles.contains(result.path)) {
+ analysisServer.priorityFileResults[result.path] = result;
+ }
+ _runDelayed(() {
+ new_sendErrorNotification(analysisServer, result);
+ });
CompilationUnit unit = result.unit;
if (unit != null) {
if (analysisServer._hasAnalysisServiceSubscription(
AnalysisService.HIGHLIGHTS, result.path)) {
- sendAnalysisNotificationHighlights(analysisServer, result.path, unit);
+ _runDelayed(() {
+ sendAnalysisNotificationHighlights(
+ analysisServer, result.path, unit);
+ });
}
if (analysisServer._hasAnalysisServiceSubscription(
AnalysisService.NAVIGATION, result.path)) {
- NavigationCollectorImpl collector = new NavigationCollectorImpl();
- computeSimpleDartNavigation(collector, unit);
- collector.createRegions();
- var params = new AnalysisNavigationParams(result.path,
- collector.regions, collector.targets, collector.files);
- analysisServer.sendNotification(params.toNotification());
+ _runDelayed(() {
+ new_sendDartNotificationNavigation(analysisServer, result);
+ });
}
}
// TODO(scheglov) Implement more notifications.
@@ -1847,6 +1896,25 @@
.add(new ContextsChangedEvent(changed: [context]));
analysisServer.schedulePerformAnalysisOperation(context);
}
+
+ /**
+ * Run [f] in a new [Future].
+ *
+ * This method is used to delay sending notifications. If there is a more
+ * important consumer of an analysis results, specifically a code completion
+ * computer, we want it to run before spending time of sending notifications.
+ *
+ * TODO(scheglov) Consider replacing this with full priority based scheduler.
+ *
+ * TODO(scheglov) Alternatively, if code completion work in a way that does
+ * not produce (at first) fully resolved unit, but only part of it - a single
+ * method, or a top-level declaration, we would not have this problem - the
+ * completion computer would be the only consumer of the partial analysis
+ * result.
+ */
+ void _runDelayed(f()) {
+ new Future(f);
+ }
}
/**
diff --git a/pkg/analysis_server/lib/src/computer/computer_highlights2.dart b/pkg/analysis_server/lib/src/computer/computer_highlights2.dart
index bfc9d66..7d67c26 100644
--- a/pkg/analysis_server/lib/src/computer/computer_highlights2.dart
+++ b/pkg/analysis_server/lib/src/computer/computer_highlights2.dart
@@ -170,7 +170,9 @@
bool _addIdentifierRegion_field(SimpleIdentifier node) {
Element element = node.bestElement;
if (element is FieldFormalParameterElement) {
- element = (element as FieldFormalParameterElement).field;
+ if (node.parent is FieldFormalParameter) {
+ element = (element as FieldFormalParameterElement).field;
+ }
}
// prepare type
HighlightRegionType type;
diff --git a/pkg/analysis_server/lib/src/computer/new_notifications.dart b/pkg/analysis_server/lib/src/computer/new_notifications.dart
index edbdc62..b4e3460 100644
--- a/pkg/analysis_server/lib/src/computer/new_notifications.dart
+++ b/pkg/analysis_server/lib/src/computer/new_notifications.dart
@@ -4,10 +4,25 @@
import 'package:analysis_server/plugin/protocol/protocol.dart' as protocol;
import 'package:analysis_server/src/analysis_server.dart' show AnalysisServer;
+import 'package:analysis_server/src/domains/analysis/navigation.dart';
+import 'package:analysis_server/src/domains/analysis/navigation_dart.dart';
import 'package:analysis_server/src/protocol_server.dart' as protocol;
import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/dart/analysis/driver.dart';
+void new_sendDartNotificationNavigation(
+ AnalysisServer analysisServer, AnalysisResult result) {
+ var unit = result.unit;
+ if (unit != null) {
+ NavigationCollectorImpl collector = new NavigationCollectorImpl();
+ computeSimpleDartNavigation(collector, unit);
+ collector.createRegions();
+ var params = new protocol.AnalysisNavigationParams(
+ result.path, collector.regions, collector.targets, collector.files);
+ analysisServer.sendNotification(params.toNotification());
+ }
+}
+
void new_sendErrorNotification(
AnalysisServer analysisServer, AnalysisResult result) {
var serverErrors = <protocol.AnalysisError>[];
diff --git a/pkg/analysis_server/lib/src/domain_analysis.dart b/pkg/analysis_server/lib/src/domain_analysis.dart
index 1c00252..9621afb 100644
--- a/pkg/analysis_server/lib/src/domain_analysis.dart
+++ b/pkg/analysis_server/lib/src/domain_analysis.dart
@@ -23,6 +23,7 @@
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/file_system/file_system.dart';
+import 'package:analyzer/src/dart/analysis/driver.dart';
import 'package:analyzer/src/generated/engine.dart' as engine;
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/task/model.dart' show ResultDescriptor;
@@ -85,13 +86,20 @@
/**
* Implement the `analysis.getHover` request.
*/
- Response getHover(Request request) {
- // prepare parameters
+ Future<Null> getHover(Request request) async {
var params = new AnalysisGetHoverParams.fromRequest(request);
- // prepare hovers
+
+ // Prepare the resolved units.
+ List<CompilationUnit> units;
+ if (server.options.enableNewAnalysisDriver) {
+ AnalysisResult result = await server.getAnalysisResult(params.file);
+ units = result != null ? [result.unit] : null;
+ } else {
+ units = server.getResolvedCompilationUnits(params.file);
+ }
+
+ // Prepare the hovers.
List<HoverInformation> hovers = <HoverInformation>[];
- List<CompilationUnit> units =
- server.getResolvedCompilationUnits(params.file);
for (CompilationUnit unit in units) {
HoverInformation hoverInformation =
new DartUnitHoverComputer(unit, params.offset).compute();
@@ -99,8 +107,10 @@
hovers.add(hoverInformation);
}
}
- // send response
- return new AnalysisGetHoverResult(hovers).toResponse(request.id);
+
+ // Send the response.
+ server.sendResponse(
+ new AnalysisGetHoverResult(hovers).toResponse(request.id));
}
/// Implement the `analysis.getLibraryDependencies` request.
@@ -187,7 +197,8 @@
if (requestName == ANALYSIS_GET_ERRORS) {
return getErrors(request);
} else if (requestName == ANALYSIS_GET_HOVER) {
- return getHover(request);
+ getHover(request);
+ return Response.DELAYED_RESPONSE;
} else if (requestName == ANALYSIS_GET_LIBRARY_DEPENDENCIES) {
return getLibraryDependencies(request);
} else if (requestName == ANALYSIS_GET_NAVIGATION) {
diff --git a/pkg/analysis_server/lib/src/domain_completion.dart b/pkg/analysis_server/lib/src/domain_completion.dart
index aefb37d..c0df56e 100644
--- a/pkg/analysis_server/lib/src/domain_completion.dart
+++ b/pkg/analysis_server/lib/src/domain_completion.dart
@@ -12,7 +12,9 @@
import 'package:analysis_server/src/provisional/completion/completion_core.dart';
import 'package:analysis_server/src/services/completion/completion_core.dart';
import 'package:analysis_server/src/services/completion/completion_performance.dart';
-import 'package:analyzer/src/generated/engine.dart';
+import 'package:analyzer/src/dart/analysis/driver.dart';
+import 'package:analyzer/src/generated/engine.dart' hide AnalysisResult;
+import 'package:analyzer/src/source/source_resource.dart';
import 'package:analyzer/src/generated/source.dart';
/**
@@ -102,23 +104,14 @@
@override
Response handleRequest(Request request) {
- if (server.options.enableNewAnalysisDriver) {
- // TODO(scheglov) implement for the new analysis driver
- String completionId = (_nextCompletionId++).toString();
- new Future(() {
- sendCompletionNotification(completionId, 0, 0, []);
- });
- return new CompletionGetSuggestionsResult(completionId)
- .toResponse(request.id);
- }
if (server.searchEngine == null) {
return new Response.noIndexGenerated(request);
}
- return runZoned(() {
+ runZoned(() {
try {
String requestName = request.method;
if (requestName == COMPLETION_GET_SUGGESTIONS) {
- return processRequest(request);
+ processRequest(request);
}
} on RequestFailure catch (exception) {
return exception.response;
@@ -130,35 +123,67 @@
exception,
stackTrace);
});
+ return Response.DELAYED_RESPONSE;
}
/**
* Process a `completion.getSuggestions` request.
*/
- Response processRequest(Request request) {
+ Future<Null> processRequest(Request request) async {
performance = new CompletionPerformance();
// extract and validate params
CompletionGetSuggestionsParams params =
new CompletionGetSuggestionsParams.fromRequest(request);
- ContextSourcePair contextSource = server.getContextSourcePair(params.file);
- AnalysisContext context = contextSource.context;
- Source source = contextSource.source;
- if (context == null || !context.exists(source)) {
- return new Response.unknownSource(request);
- }
- TimestampedData<String> contents = context.getContents(source);
- if (params.offset < 0 || params.offset > contents.data.length) {
- return new Response.invalidParameter(
- request,
- 'params.offset',
- 'Expected offset between 0 and source length inclusive,'
- ' but found ${params.offset}');
+
+ AnalysisResult result;
+ AnalysisContext context;
+ Source source;
+ if (server.options.enableNewAnalysisDriver) {
+ result = await server.getAnalysisResult(params.file);
+
+ if (result == null) {
+ server.sendResponse(new Response.unknownSource(request));
+ return;
+ }
+
+ if (params.offset < 0 || params.offset > result.content.length) {
+ server.sendResponse(new Response.invalidParameter(
+ request,
+ 'params.offset',
+ 'Expected offset between 0 and source length inclusive,'
+ ' but found ${params.offset}'));
+ return;
+ }
+
+ source = new FileSource(
+ server.resourceProvider.getFile(result.path), result.uri);
+ } else {
+ ContextSourcePair contextSource =
+ server.getContextSourcePair(params.file);
+
+ context = contextSource.context;
+ source = contextSource.source;
+ if (context == null || !context.exists(source)) {
+ server.sendResponse(new Response.unknownSource(request));
+ return;
+ }
+
+ TimestampedData<String> contents = context.getContents(source);
+ if (params.offset < 0 || params.offset > contents.data.length) {
+ server.sendResponse(new Response.invalidParameter(
+ request,
+ 'params.offset',
+ 'Expected offset between 0 and source length inclusive,'
+ ' but found ${params.offset}'));
+ return;
+ }
}
recordRequest(performance, context, source, params.offset);
CompletionRequestImpl completionRequest = new CompletionRequestImpl(
+ result,
context,
server.resourceProvider,
server.searchEngine,
@@ -170,6 +195,10 @@
_abortCurrentRequest();
_currentRequest = completionRequest;
+ // initial response without results
+ server.sendResponse(new CompletionGetSuggestionsResult(completionId)
+ .toResponse(request.id));
+
// Compute suggestions in the background
computeSuggestions(completionRequest).then((CompletionResult result) {
const SEND_NOTIFICATION_TAG = 'send notification';
@@ -188,10 +217,6 @@
_currentRequest = null;
}
});
-
- // initial response without results
- return new CompletionGetSuggestionsResult(completionId)
- .toResponse(request.id);
}
/**
diff --git a/pkg/analysis_server/lib/src/edit/edit_domain.dart b/pkg/analysis_server/lib/src/edit/edit_domain.dart
index 5906cd1..6d3bec4 100644
--- a/pkg/analysis_server/lib/src/edit/edit_domain.dart
+++ b/pkg/analysis_server/lib/src/edit/edit_domain.dart
@@ -7,13 +7,17 @@
import 'dart:async';
import 'package:analysis_server/plugin/edit/assist/assist_core.dart';
+import 'package:analysis_server/plugin/edit/assist/assist_dart.dart';
import 'package:analysis_server/plugin/edit/fix/fix_core.dart';
+import 'package:analysis_server/plugin/edit/fix/fix_dart.dart';
import 'package:analysis_server/src/analysis_server.dart';
import 'package:analysis_server/src/collections.dart';
import 'package:analysis_server/src/constants.dart';
import 'package:analysis_server/src/protocol_server.dart' hide Element;
import 'package:analysis_server/src/services/correction/assist.dart';
+import 'package:analysis_server/src/services/correction/assist_internal.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
+import 'package:analysis_server/src/services/correction/fix_internal.dart';
import 'package:analysis_server/src/services/correction/organize_directives.dart';
import 'package:analysis_server/src/services/correction/sort_members.dart';
import 'package:analysis_server/src/services/correction/status.dart';
@@ -22,6 +26,8 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/error/error.dart' as engine;
+import 'package:analyzer/file_system/file_system.dart';
+import 'package:analyzer/src/dart/analysis/driver.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart' as engine;
import 'package:analyzer/src/error/codes.dart' as engine;
import 'package:analyzer/src/generated/engine.dart' as engine;
@@ -131,63 +137,98 @@
}
Future getAssists(Request request) async {
- if (server.options.enableNewAnalysisDriver) {
- // TODO(scheglov) implement for the new analysis driver
- return;
- }
EditGetAssistsParams params = new EditGetAssistsParams.fromRequest(request);
- ContextSourcePair pair = server.getContextSourcePair(params.file);
- engine.AnalysisContext context = pair.context;
- Source source = pair.source;
- List<SourceChange> changes = <SourceChange>[];
- if (context != null && source != null) {
- List<Assist> assists = await computeAssists(
- server.serverPlugin, context, source, params.offset, params.length);
- assists.forEach((Assist assist) {
- changes.add(assist.change);
- });
+ List<Assist> assists;
+ if (server.options.enableNewAnalysisDriver) {
+ AnalysisResult result = await server.getAnalysisResult(params.file);
+ CompilationUnit unit = result.unit;
+ DartAssistContext dartAssistContext = new _DartAssistContextForValues(
+ unit.element.source,
+ params.offset,
+ params.length,
+ unit.element.context,
+ unit);
+ try {
+ AssistProcessor processor = new AssistProcessor(dartAssistContext);
+ assists = await processor.compute();
+ } catch (_) {}
+ } else {
+ ContextSourcePair pair = server.getContextSourcePair(params.file);
+ engine.AnalysisContext context = pair.context;
+ Source source = pair.source;
+ if (context != null && source != null) {
+ assists = await computeAssists(
+ server.serverPlugin, context, source, params.offset, params.length);
+ }
}
+ // Send the assist changes.
+ List<SourceChange> changes = <SourceChange>[];
+ assists?.forEach((Assist assist) {
+ changes.add(assist.change);
+ });
Response response =
new EditGetAssistsResult(changes).toResponse(request.id);
server.sendResponse(response);
}
Future getFixes(Request request) async {
- if (server.options.enableNewAnalysisDriver) {
- // TODO(scheglov) implement for the new analysis driver
- return;
- }
var params = new EditGetFixesParams.fromRequest(request);
String file = params.file;
int offset = params.offset;
- // add fixes
+
List<AnalysisErrorFixes> errorFixesList = <AnalysisErrorFixes>[];
- List<CompilationUnit> units = server.getResolvedCompilationUnits(file);
- for (CompilationUnit unit in units) {
- engine.AnalysisErrorInfo errorInfo = server.getErrors(file);
- if (errorInfo != null) {
- LineInfo lineInfo = errorInfo.lineInfo;
- int requestLine = lineInfo.getLocation(offset).lineNumber;
- for (engine.AnalysisError error in errorInfo.errors) {
- int errorLine = lineInfo.getLocation(error.offset).lineNumber;
- if (errorLine == requestLine) {
- List<Fix> fixes = await computeFixes(server.serverPlugin,
- server.resourceProvider, unit.element.context, error);
- if (fixes.isNotEmpty) {
- AnalysisError serverError =
- newAnalysisError_fromEngine(lineInfo, error);
- AnalysisErrorFixes errorFixes =
- new AnalysisErrorFixes(serverError);
- errorFixesList.add(errorFixes);
- fixes.forEach((fix) {
- errorFixes.fixes.add(fix.change);
- });
+ if (server.options.enableNewAnalysisDriver) {
+ AnalysisResult result = await server.getAnalysisResult(file);
+ CompilationUnit unit = result.unit;
+ LineInfo lineInfo = result.lineInfo;
+ int requestLine = lineInfo.getLocation(offset).lineNumber;
+ for (engine.AnalysisError error in result.errors) {
+ int errorLine = lineInfo.getLocation(error.offset).lineNumber;
+ if (errorLine == requestLine) {
+ var context = new _DartFixContextImpl(
+ server.resourceProvider, unit.element.context, unit, error);
+ List<Fix> fixes =
+ await new DefaultFixContributor().internalComputeFixes(context);
+ if (fixes.isNotEmpty) {
+ AnalysisError serverError =
+ newAnalysisError_fromEngine(lineInfo, error);
+ AnalysisErrorFixes errorFixes = new AnalysisErrorFixes(serverError);
+ errorFixesList.add(errorFixes);
+ fixes.forEach((fix) {
+ errorFixes.fixes.add(fix.change);
+ });
+ }
+ }
+ }
+ } else {
+ List<CompilationUnit> units = server.getResolvedCompilationUnits(file);
+ for (CompilationUnit unit in units) {
+ engine.AnalysisErrorInfo errorInfo = server.getErrors(file);
+ if (errorInfo != null) {
+ LineInfo lineInfo = errorInfo.lineInfo;
+ int requestLine = lineInfo.getLocation(offset).lineNumber;
+ for (engine.AnalysisError error in errorInfo.errors) {
+ int errorLine = lineInfo.getLocation(error.offset).lineNumber;
+ if (errorLine == requestLine) {
+ List<Fix> fixes = await computeFixes(server.serverPlugin,
+ server.resourceProvider, unit.element.context, error);
+ if (fixes.isNotEmpty) {
+ AnalysisError serverError =
+ newAnalysisError_fromEngine(lineInfo, error);
+ AnalysisErrorFixes errorFixes =
+ new AnalysisErrorFixes(serverError);
+ errorFixesList.add(errorFixes);
+ fixes.forEach((fix) {
+ errorFixes.fixes.add(fix.change);
+ });
+ }
}
}
}
}
}
- // respond
+
+ // Send the response.
server.sendResponse(
new EditGetFixesResult(errorFixesList).toResponse(request.id));
}
@@ -211,7 +252,8 @@
} else if (requestName == EDIT_ORGANIZE_DIRECTIVES) {
return organizeDirectives(request);
} else if (requestName == EDIT_SORT_MEMBERS) {
- return sortMembers(request);
+ sortMembers(request);
+ return Response.DELAYED_RESPONSE;
}
} on RequestFailure catch (exception) {
return exception.response;
@@ -251,40 +293,60 @@
return new EditOrganizeDirectivesResult(fileEdit).toResponse(request.id);
}
- Response sortMembers(Request request) {
+ Future<Null> sortMembers(Request request) async {
var params = new EditSortMembersParams.fromRequest(request);
// prepare file
String file = params.file;
if (!engine.AnalysisEngine.isDartFileName(file)) {
- return new Response.sortMembersInvalidFile(request);
+ server.sendResponse(new Response.sortMembersInvalidFile(request));
}
- // prepare location
- ContextSourcePair contextSource = server.getContextSourcePair(file);
- engine.AnalysisContext context = contextSource.context;
- Source source = contextSource.source;
- if (context == null || source == null) {
- return new Response.sortMembersInvalidFile(request);
- }
- // prepare parsed unit
+ // Prepare the file information.
+ int fileStamp;
+ String code;
CompilationUnit unit;
- try {
- unit = context.parseCompilationUnit(source);
- } catch (e) {
- return new Response.sortMembersInvalidFile(request);
+ List<engine.AnalysisError> errors;
+ if (server.options.enableNewAnalysisDriver) {
+ AnalysisDriver driver = server.getAnalysisDriver(file);
+ ParseResult result = await driver.parseFile(file);
+ fileStamp = -1;
+ code = result.content;
+ unit = result.unit;
+ errors = result.errors;
+ } else {
+ // prepare location
+ ContextSourcePair contextSource = server.getContextSourcePair(file);
+ engine.AnalysisContext context = contextSource.context;
+ Source source = contextSource.source;
+ if (context == null || source == null) {
+ server.sendResponse(new Response.sortMembersInvalidFile(request));
+ return;
+ }
+ // prepare code
+ fileStamp = context.getModificationStamp(source);
+ code = context.getContents(source).data;
+ // prepare parsed unit
+ try {
+ unit = context.parseCompilationUnit(source);
+ } catch (e) {
+ server.sendResponse(new Response.sortMembersInvalidFile(request));
+ return;
+ }
+ // Get the errors.
+ errors = context.getErrors(source).errors;
}
- // check if there are scan/parse errors in the file
- engine.AnalysisErrorInfo errors = context.getErrors(source);
- int numScanParseErrors = _getNumberOfScanParseErrors(errors.errors);
+ // Check if there are scan/parse errors in the file.
+ int numScanParseErrors = _getNumberOfScanParseErrors(errors);
if (numScanParseErrors != 0) {
- return new Response.sortMembersParseErrors(request, numScanParseErrors);
+ server.sendResponse(
+ new Response.sortMembersParseErrors(request, numScanParseErrors));
+ return;
}
- // do sort
- int fileStamp = context.getModificationStamp(source);
- String code = context.getContents(source).data;
+ // Do sort.
MemberSorter sorter = new MemberSorter(code, unit);
List<SourceEdit> edits = sorter.sort();
SourceFileEdit fileEdit = new SourceFileEdit(file, fileStamp, edits: edits);
- return new EditSortMembersResult(fileEdit).toResponse(request.id);
+ server.sendResponse(
+ new EditSortMembersResult(fileEdit).toResponse(request.id));
}
Response _getAvailableRefactorings(Request request) {
@@ -369,6 +431,50 @@
}
/**
+ * Implementation of [DartAssistContext] that is based on the values passed
+ * in the constructor, as opposite to be partially based on [AssistContext].
+ */
+class _DartAssistContextForValues implements DartAssistContext {
+ @override
+ final Source source;
+
+ @override
+ final int selectionOffset;
+
+ @override
+ final int selectionLength;
+
+ @override
+ final engine.AnalysisContext analysisContext;
+
+ @override
+ final CompilationUnit unit;
+
+ _DartAssistContextForValues(this.source, this.selectionOffset,
+ this.selectionLength, this.analysisContext, this.unit);
+}
+
+/**
+ * And implementation of [DartFixContext].
+ */
+class _DartFixContextImpl implements DartFixContext {
+ @override
+ final ResourceProvider resourceProvider;
+
+ @override
+ final engine.AnalysisContext analysisContext;
+
+ @override
+ final CompilationUnit unit;
+
+ @override
+ final engine.AnalysisError error;
+
+ _DartFixContextImpl(
+ this.resourceProvider, this.analysisContext, this.unit, this.error);
+}
+
+/**
* An object managing a single [Refactoring] instance.
*
* The instance is identified by its kind, file, offset and length.
diff --git a/pkg/analysis_server/lib/src/provisional/completion/completion_core.dart b/pkg/analysis_server/lib/src/provisional/completion/completion_core.dart
index 1aa1c9f..06eb530 100644
--- a/pkg/analysis_server/lib/src/provisional/completion/completion_core.dart
+++ b/pkg/analysis_server/lib/src/provisional/completion/completion_core.dart
@@ -9,6 +9,7 @@
import 'package:analysis_server/plugin/protocol/protocol.dart';
import 'package:analysis_server/src/services/search/search_engine.dart';
import 'package:analyzer/file_system/file_system.dart';
+import 'package:analyzer/src/dart/analysis/driver.dart';
import 'package:analyzer/src/generated/engine.dart' show AnalysisContext;
import 'package:analyzer/src/generated/source.dart';
@@ -71,6 +72,12 @@
ResourceProvider get resourceProvider;
/**
+ * The analysis result for the file in which the completion is being
+ * requested.
+ */
+ AnalysisResult get result;
+
+ /**
* Return the search engine.
*/
SearchEngine get searchEngine;
diff --git a/pkg/analysis_server/lib/src/services/completion/completion_core.dart b/pkg/analysis_server/lib/src/services/completion/completion_core.dart
index b79a9d8..c43a144 100644
--- a/pkg/analysis_server/lib/src/services/completion/completion_core.dart
+++ b/pkg/analysis_server/lib/src/services/completion/completion_core.dart
@@ -8,7 +8,8 @@
import 'package:analysis_server/src/services/completion/completion_performance.dart';
import 'package:analysis_server/src/services/search/search_engine.dart';
import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer/src/generated/engine.dart';
+import 'package:analyzer/src/dart/analysis/driver.dart';
+import 'package:analyzer/src/generated/engine.dart' hide AnalysisResult;
import 'package:analyzer/src/generated/source.dart';
/**
@@ -16,6 +17,9 @@
*/
class CompletionRequestImpl implements CompletionRequest {
@override
+ final AnalysisResult result;
+
+ @override
final AnalysisContext context;
@override
@@ -63,14 +67,20 @@
/**
* Initialize a newly created completion request based on the given arguments.
*/
- CompletionRequestImpl(AnalysisContext context, this.resourceProvider,
- this.searchEngine, Source source, int offset, this.performance)
+ CompletionRequestImpl(
+ this.result,
+ AnalysisContext context,
+ this.resourceProvider,
+ this.searchEngine,
+ Source source,
+ int offset,
+ this.performance)
: this.context = context,
this.source = source,
this.offset = offset,
replacementOffset = offset,
replacementLength = 0,
- sourceModificationStamp = context.getModificationStamp(source);
+ sourceModificationStamp = context?.getModificationStamp(source);
/**
* Return the original text from the [replacementOffset] to the [offset]
@@ -95,7 +105,7 @@
if (_aborted) {
throw new AbortCompletion();
}
- if (sourceModificationStamp != context.getModificationStamp(source)) {
+ if (sourceModificationStamp != context?.getModificationStamp(source)) {
_aborted = true;
throw new AbortCompletion();
}
diff --git a/pkg/analysis_server/lib/src/services/completion/dart/common_usage_sorter.dart b/pkg/analysis_server/lib/src/services/completion/dart/common_usage_sorter.dart
index 719221e..67f7137 100644
--- a/pkg/analysis_server/lib/src/services/completion/dart/common_usage_sorter.dart
+++ b/pkg/analysis_server/lib/src/services/completion/dart/common_usage_sorter.dart
@@ -46,18 +46,24 @@
}
CompletionTarget _getCompletionTarget(CompletionRequest request) {
- // TODO (danrubel) get cached completion target
- var libSrcs = request.context.getLibrariesContaining(request.source);
- if (libSrcs.length == 0) {
- return null;
- }
- var libElem = request.context.getResult(libSrcs[0], LIBRARY_ELEMENT1);
- if (libElem is LibraryElement) {
- var unit = request.context.getResult(
- new LibrarySpecificUnit(libElem.source, request.source),
- RESOLVED_UNIT5);
- if (unit is CompilationUnit) {
- return new CompletionTarget.forOffset(unit, request.offset);
+ if (request.result != null) {
+ var unit = request.result.unit;
+ return new CompletionTarget.forOffset(unit, request.offset);
+ } else {
+ // TODO (danrubel) get cached completion target
+ var libSrcs = request.context.getLibrariesContaining(request.source);
+ if (libSrcs.length == 0) {
+ return null;
+ }
+ LibraryElement libElem =
+ request.context.getResult(libSrcs[0], LIBRARY_ELEMENT1);
+ if (libElem is LibraryElement) {
+ var unit = request.context.getResult(
+ new LibrarySpecificUnit(libElem.source, request.source),
+ RESOLVED_UNIT5);
+ if (unit is CompilationUnit) {
+ return new CompletionTarget.forOffset(unit, request.offset);
+ }
}
}
return null;
diff --git a/pkg/analysis_server/lib/src/services/completion/dart/completion_manager.dart b/pkg/analysis_server/lib/src/services/completion/dart/completion_manager.dart
index ef95f10..069b071 100644
--- a/pkg/analysis_server/lib/src/services/completion/dart/completion_manager.dart
+++ b/pkg/analysis_server/lib/src/services/completion/dart/completion_manager.dart
@@ -25,8 +25,9 @@
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/context/context.dart' show AnalysisFutureHelper;
+import 'package:analyzer/src/dart/analysis/driver.dart';
import 'package:analyzer/src/dart/ast/token.dart';
-import 'package:analyzer/src/generated/engine.dart';
+import 'package:analyzer/src/generated/engine.dart' hide AnalysisResult;
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/task/dart.dart';
import 'package:analyzer/task/dart.dart';
@@ -106,6 +107,9 @@
*/
class DartCompletionRequestImpl implements DartCompletionRequest {
@override
+ final AnalysisResult result;
+
+ @override
final AnalysisContext context;
@override
@@ -158,6 +162,7 @@
final CompletionPerformance performance;
DartCompletionRequestImpl._(
+ this.result,
this.context,
this.resourceProvider,
this.searchEngine,
@@ -254,12 +259,17 @@
// Resolve declarations in the target unit
// TODO(danrubel) resolve the expression or containing method
// rather than the entire compilation unit
- CompilationUnit resolvedUnit = await _computeAsync(
- this,
- new LibrarySpecificUnit(librarySource, source),
- RESOLVED_UNIT,
- performance,
- 'resolve expression');
+ CompilationUnit resolvedUnit;
+ if (result != null) {
+ resolvedUnit = result.unit;
+ } else {
+ resolvedUnit = await _computeAsync(
+ this,
+ new LibrarySpecificUnit(librarySource, source),
+ RESOLVED_UNIT,
+ performance,
+ 'resolve expression');
+ }
// TODO(danrubel) determine if the underlying source has been modified
// in a way that invalidates the completion request
@@ -302,6 +312,10 @@
if (_resolvedUnits != null) {
return _resolvedUnits;
}
+ if (result != null) {
+ _resolvedUnits = result.unit.element.library.units;
+ return _resolvedUnits;
+ }
LibraryElement libElem = libraryElement;
if (libElem == null) {
return null;
@@ -365,35 +379,43 @@
const BUILD_REQUEST_TAG = 'build DartCompletionRequest';
performance.logStartTime(BUILD_REQUEST_TAG);
- Source source = request.source;
- AnalysisContext context = request.context;
-
- const PARSE_TAG = 'parse unit';
- performance.logStartTime(PARSE_TAG);
- CompilationUnit unit = request.context.computeResult(source, PARSED_UNIT);
- performance.logElapseTime(PARSE_TAG);
-
Source libSource;
- if (unit.directives.any((d) => d is PartOfDirective)) {
- List<Source> libraries = context.getLibrariesContaining(source);
- if (libraries.isNotEmpty) {
- libSource = libraries[0];
- }
+ CompilationUnit unit;
+ if (request.context == null) {
+ unit = request.result.unit;
+ // TODO(scheglov) support for parts
+ libSource = unit.element.source;
} else {
- libSource = source;
- }
+ Source source = request.source;
+ AnalysisContext context = request.context;
- // Most (all?) contributors need declarations in scope to be resolved
- if (libSource != null) {
- unit = await _computeAsync(
- request,
- new LibrarySpecificUnit(libSource, source),
- resultDescriptor ?? RESOLVED_UNIT5,
- performance,
- 'resolve declarations');
+ const PARSE_TAG = 'parse unit';
+ performance.logStartTime(PARSE_TAG);
+ unit = request.context.computeResult(source, PARSED_UNIT);
+ performance.logElapseTime(PARSE_TAG);
+
+ if (unit.directives.any((d) => d is PartOfDirective)) {
+ List<Source> libraries = context.getLibrariesContaining(source);
+ if (libraries.isNotEmpty) {
+ libSource = libraries[0];
+ }
+ } else {
+ libSource = source;
+ }
+
+ // Most (all?) contributors need declarations in scope to be resolved
+ if (libSource != null) {
+ unit = await _computeAsync(
+ request,
+ new LibrarySpecificUnit(libSource, source),
+ resultDescriptor ?? RESOLVED_UNIT5,
+ performance,
+ 'resolve declarations');
+ }
}
DartCompletionRequestImpl dartRequest = new DartCompletionRequestImpl._(
+ request.result,
request.context,
request.resourceProvider,
request.searchEngine,
diff --git a/pkg/analysis_server/lib/src/services/completion/dart/local_reference_contributor.dart b/pkg/analysis_server/lib/src/services/completion/dart/local_reference_contributor.dart
index c69d806..5f78297 100644
--- a/pkg/analysis_server/lib/src/services/completion/dart/local_reference_contributor.dart
+++ b/pkg/analysis_server/lib/src/services/completion/dart/local_reference_contributor.dart
@@ -209,23 +209,22 @@
// If user typed identifier starting with '_'
// then do not suppress the relevance of private members
- var contents = request.context.getContents(request.source);
- if (contents != null) {
- String data = contents.data;
- int offset = request.offset;
- if (data != null && 0 < offset && offset <= data.length) {
- bool isIdentifierChar(int index) {
- int code = data.codeUnitAt(index);
- return isLetterOrDigit(code) || code == CHAR_UNDERSCORE;
- }
+ var data = request.result != null
+ ? request.result.content
+ : request.context.getContents(request.source)?.data;
+ int offset = request.offset;
+ if (data != null && 0 < offset && offset <= data.length) {
+ bool isIdentifierChar(int index) {
+ int code = data.codeUnitAt(index);
+ return isLetterOrDigit(code) || code == CHAR_UNDERSCORE;
+ }
- if (isIdentifierChar(offset - 1)) {
- while (offset > 0 && isIdentifierChar(offset - 1)) {
- --offset;
- }
- if (data.codeUnitAt(offset) == CHAR_UNDERSCORE) {
- privateMemberRelevance = null;
- }
+ if (isIdentifierChar(offset - 1)) {
+ while (offset > 0 && isIdentifierChar(offset - 1)) {
+ --offset;
+ }
+ if (data.codeUnitAt(offset) == CHAR_UNDERSCORE) {
+ privateMemberRelevance = null;
}
}
}
diff --git a/pkg/analysis_server/test/analysis/get_hover_test.dart b/pkg/analysis_server/test/analysis/get_hover_test.dart
index f97ae90..7f48ae2 100644
--- a/pkg/analysis_server/test/analysis/get_hover_test.dart
+++ b/pkg/analysis_server/test/analysis/get_hover_test.dart
@@ -29,7 +29,7 @@
await waitForTasksFinished();
Request request =
new AnalysisGetHoverParams(testFile, offset).toRequest('0');
- Response response = handleSuccessfulRequest(request);
+ Response response = await waitResponse(request);
var result = new AnalysisGetHoverResult.fromResponse(response);
List<HoverInformation> hovers = result.hovers;
return hovers.isNotEmpty ? hovers.first : null;
diff --git a/pkg/analysis_server/test/analysis/notification_highlights_test2.dart b/pkg/analysis_server/test/analysis/notification_highlights_test2.dart
index 2618777..28568ef 100644
--- a/pkg/analysis_server/test/analysis/notification_highlights_test2.dart
+++ b/pkg/analysis_server/test/analysis/notification_highlights_test2.dart
@@ -911,6 +911,23 @@
assertHasRegion(HighlightRegionType.PARAMETER_REFERENCE, 'p = 42');
}
+ test_PARAMETER_named() async {
+ addTestFile('''
+class C {
+ final int aaa;
+ C({this.aaa, int bbb});
+}
+main() {
+ new C(aaa: 1, bbb: 2);
+}
+''');
+ await prepareHighlights();
+ assertHasRegion(HighlightRegionType.INSTANCE_FIELD_REFERENCE, 'aaa,');
+ assertHasRegion(HighlightRegionType.PARAMETER_DECLARATION, 'bbb}');
+ assertHasRegion(HighlightRegionType.PARAMETER_REFERENCE, 'aaa: 1');
+ assertHasRegion(HighlightRegionType.PARAMETER_REFERENCE, 'bbb: 2');
+ }
+
test_SETTER_DECLARATION() async {
addTestFile('''
set aaa(x) {}
diff --git a/pkg/analysis_server/test/domain_completion_test.dart b/pkg/analysis_server/test/domain_completion_test.dart
index ef51507..b3d85f2 100644
--- a/pkg/analysis_server/test/domain_completion_test.dart
+++ b/pkg/analysis_server/test/domain_completion_test.dart
@@ -123,13 +123,13 @@
c^''');
// Make a request for suggestions
- Request request =
+ Request request1 =
new CompletionGetSuggestionsParams(testFile, completionOffset)
.toRequest('7');
- Response response = handleSuccessfulRequest(request);
- var result1 = new CompletionGetSuggestionsResult.fromResponse(response);
+ Response response1 = await waitResponse(request1);
+ var result1 = new CompletionGetSuggestionsResult.fromResponse(response1);
var completionId1 = result1.id;
- assertValidId(response.id);
+ assertValidId(completionId1);
// Perform some analysis but assert that no suggestions have yet been made
completionId = completionId1;
@@ -141,7 +141,7 @@
Request request2 =
new CompletionGetSuggestionsParams(testFile, completionOffset)
.toRequest('8');
- Response response2 = handleSuccessfulRequest(request2);
+ Response response2 = await waitResponse(request2);
var result2 = new CompletionGetSuggestionsResult.fromResponse(response2);
var completionId2 = result2.id;
assertValidId(completionId2);
@@ -164,7 +164,7 @@
Request request =
new CompletionGetSuggestionsParams(testFile, completionOffset)
.toRequest('0');
- Response response = handleSuccessfulRequest(request);
+ Response response = await waitResponse(request);
completionId = response.id;
assertValidId(completionId);
@@ -227,7 +227,7 @@
{testFile: new AddContentOverlay(revisedContent)}).toRequest('add1'));
// Request code completion immediately after edit
- Response response = handleSuccessfulRequest(
+ Response response = await waitResponse(
new CompletionGetSuggestionsParams(testFile, completionOffset)
.toRequest('0'));
completionId = response.id;
@@ -466,12 +466,12 @@
});
}
- test_offset_past_eof() {
+ test_offset_past_eof() async {
addTestFile('main() { }', offset: 300);
Request request =
new CompletionGetSuggestionsParams(testFile, completionOffset)
.toRequest('0');
- Response response = handler.handleRequest(request);
+ Response response = await waitResponse(request);
expect(response.id, '0');
expect(response.error.code, RequestErrorCode.INVALID_PARAMETER);
}
diff --git a/pkg/analysis_server/test/domain_completion_util.dart b/pkg/analysis_server/test/domain_completion_util.dart
index bd55b72..e95b14f 100644
--- a/pkg/analysis_server/test/domain_completion_util.dart
+++ b/pkg/analysis_server/test/domain_completion_util.dart
@@ -14,13 +14,13 @@
import 'package:test/test.dart';
import 'analysis_abstract.dart';
-import 'mocks.dart';
class AbstractCompletionDomainTest extends AbstractAnalysisTest {
String completionId;
int completionOffset;
int replacementOffset;
int replacementLength;
+ Map<String, Completer<Null>> receivedSuggestionsCompleters = {};
List<CompletionSuggestion> suggestions = [];
bool suggestionsDone = false;
Map<String, List<CompletionSuggestion>> allSuggestions = {};
@@ -82,34 +82,33 @@
return createMemoryIndex();
}
- Future getSuggestions() {
- return waitForTasksFinished().then((_) {
- Request request =
- new CompletionGetSuggestionsParams(testFile, completionOffset)
- .toRequest('0');
- Response response = handleSuccessfulRequest(request);
- completionId = response.id;
- assertValidId(completionId);
- return pumpEventQueue().then((_) {
- expect(suggestionsDone, isTrue);
- });
- });
+ Future getSuggestions() async {
+ await waitForTasksFinished();
+
+ Request request =
+ new CompletionGetSuggestionsParams(testFile, completionOffset)
+ .toRequest('0');
+ Response response = await waitResponse(request);
+ var result = new CompletionGetSuggestionsResult.fromResponse(response);
+ completionId = result.id;
+ assertValidId(completionId);
+ await _getResultsCompleter(completionId).future;
+ expect(suggestionsDone, isTrue);
}
- void processNotification(Notification notification) {
+ processNotification(Notification notification) async {
if (notification.event == COMPLETION_RESULTS) {
var params = new CompletionResultsParams.fromNotification(notification);
String id = params.id;
assertValidId(id);
- if (id == completionId) {
- expect(suggestionsDone, isFalse);
- replacementOffset = params.replacementOffset;
- replacementLength = params.replacementLength;
- suggestionsDone = params.isLast;
- expect(suggestionsDone, isNotNull);
- suggestions = params.results;
- }
+ replacementOffset = params.replacementOffset;
+ replacementLength = params.replacementLength;
+ suggestionsDone = params.isLast;
+ expect(suggestionsDone, isNotNull);
+ suggestions = params.results;
+ expect(allSuggestions.containsKey(id), isFalse);
allSuggestions[id] = params.results;
+ _getResultsCompleter(id).complete(null);
} else if (notification.event == SERVER_ERROR) {
fail('server error: ${notification.toJson()}');
}
@@ -121,4 +120,9 @@
createProject();
handler = new CompletionDomainHandler(server);
}
+
+ Completer<Null> _getResultsCompleter(String id) {
+ return receivedSuggestionsCompleters.putIfAbsent(
+ id, () => new Completer<Null>());
+ }
}
diff --git a/pkg/analysis_server/test/edit/sort_members_test.dart b/pkg/analysis_server/test/edit/sort_members_test.dart
index c5651fa..b246d82 100644
--- a/pkg/analysis_server/test/edit/sort_members_test.dart
+++ b/pkg/analysis_server/test/edit/sort_members_test.dart
@@ -37,7 +37,7 @@
test_BAD_doesNotExist() async {
Request request =
new EditSortMembersParams('/no/such/file.dart').toRequest('0');
- Response response = handler.handleRequest(request);
+ Response response = await waitResponse(request);
expect(response,
isResponseFailure('0', RequestErrorCode.SORT_MEMBERS_INVALID_FILE));
}
@@ -49,7 +49,7 @@
}
''');
Request request = new EditSortMembersParams(testFile).toRequest('0');
- Response response = handler.handleRequest(request);
+ Response response = await waitResponse(request);
expect(response,
isResponseFailure('0', RequestErrorCode.SORT_MEMBERS_PARSE_ERRORS));
}
@@ -57,7 +57,7 @@
test_BAD_notDartFile() async {
Request request =
new EditSortMembersParams('/not-a-Dart-file.txt').toRequest('0');
- Response response = handler.handleRequest(request);
+ Response response = await waitResponse(request);
expect(response,
isResponseFailure('0', RequestErrorCode.SORT_MEMBERS_INVALID_FILE));
}
@@ -192,14 +192,14 @@
}
Future _assertSorted(String expectedCode) async {
- _requestSort();
+ await _requestSort();
String resultCode = SourceEdit.applySequence(testCode, fileEdit.edits);
expect(resultCode, expectedCode);
}
- void _requestSort() {
+ Future _requestSort() async {
Request request = new EditSortMembersParams(testFile).toRequest('0');
- Response response = handleSuccessfulRequest(request);
+ Response response = await waitResponse(request);
var result = new EditSortMembersResult.fromResponse(response);
fileEdit = result.edit;
}
diff --git a/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart b/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart
index c6982f3..1a5fac8 100644
--- a/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart
+++ b/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart
@@ -454,6 +454,7 @@
Future computeSuggestions([int times = 200]) async {
context.analysisPriorityOrder = [testSource];
CompletionRequestImpl baseRequest = new CompletionRequestImpl(
+ null,
context,
provider,
searchEngine,
diff --git a/pkg/analysis_server/test/services/completion/dart/completion_manager_test.dart b/pkg/analysis_server/test/services/completion/dart/completion_manager_test.dart
index 4d624b7..67e691a 100644
--- a/pkg/analysis_server/test/services/completion/dart/completion_manager_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/completion_manager_test.dart
@@ -56,6 +56,7 @@
// Build the request
CompletionRequestImpl baseRequest = new CompletionRequestImpl(
+ null,
context,
provider,
searchEngine,
diff --git a/pkg/analyzer/lib/error/error.dart b/pkg/analyzer/lib/error/error.dart
index 49c0179..ce8b384 100644
--- a/pkg/analyzer/lib/error/error.dart
+++ b/pkg/analyzer/lib/error/error.dart
@@ -869,6 +869,13 @@
StrongModeCode.INFERRED_TYPE_ALLOCATION,
StrongModeCode.INFERRED_TYPE_CLOSURE,
StrongModeCode.INFERRED_TYPE_LITERAL,
+ StrongModeCode.INVALID_CAST_LITERAL,
+ StrongModeCode.INVALID_CAST_LITERAL_LIST,
+ StrongModeCode.INVALID_CAST_LITERAL_MAP,
+ StrongModeCode.INVALID_CAST_FUNCTION_EXPR,
+ StrongModeCode.INVALID_CAST_NEW_EXPR,
+ StrongModeCode.INVALID_CAST_METHOD,
+ StrongModeCode.INVALID_CAST_FUNCTION,
StrongModeCode.INVALID_FIELD_OVERRIDE,
StrongModeCode.INVALID_METHOD_OVERRIDE,
StrongModeCode.INVALID_METHOD_OVERRIDE_FROM_BASE,
@@ -876,7 +883,6 @@
StrongModeCode.INVALID_PARAMETER_DECLARATION,
StrongModeCode.INVALID_SUPER_INVOCATION,
StrongModeCode.NON_GROUND_TYPE_CHECK_INFO,
- StrongModeCode.STATIC_TYPE_ERROR,
StrongModeCode.UNSAFE_BLOCK_CLOSURE_INFERENCE,
TodoCode.TODO,
];
diff --git a/pkg/analyzer/lib/src/dart/analysis/driver.dart b/pkg/analyzer/lib/src/dart/analysis/driver.dart
index 7033335..ee355c4 100644
--- a/pkg/analyzer/lib/src/dart/analysis/driver.dart
+++ b/pkg/analyzer/lib/src/dart/analysis/driver.dart
@@ -8,6 +8,7 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/context/context.dart';
import 'package:analyzer/src/dart/analysis/byte_store.dart';
@@ -384,6 +385,26 @@
}
/**
+ * Return the [Future] that completes with a [ParseResult] for the file
+ * with the given [path].
+ *
+ * The [path] must be absolute and normalized.
+ *
+ * The [path] can be any file - explicitly or implicitly analyzed, or neither.
+ *
+ * The parsing is performed in the method itself, and the result is not
+ * produced through the [results] stream (just because it is not a fully
+ * resolved unit).
+ */
+ Future<ParseResult> parseFile(String path) async {
+ FileState file = _fsState.getFileForPath(path);
+ RecordingErrorListener listener = new RecordingErrorListener();
+ CompilationUnit unit = file.parse(listener);
+ return new ParseResult(file.path, file.uri, file.content, file.contentHash,
+ unit.lineInfo, unit, listener.errors);
+ }
+
+ /**
* Remove the file with the given [path] from the list of files to analyze.
*
* The [path] must be absolute and normalized.
@@ -415,8 +436,9 @@
* We need to clean this up.
*/
void _addToStoreUnlinked(
- SummaryDataStore store, String uri, UnlinkedUnit unlinked) {
- store.unlinkedMap[uri] = unlinked;
+ SummaryDataStore store, Uri uri, UnlinkedUnit unlinked) {
+ String uriStr = uri.toString();
+ store.unlinkedMap[uriStr] = unlinked;
}
/**
@@ -429,7 +451,7 @@
AnalysisResult _computeAnalysisResult(String path, {bool withUnit: false}) {
// If we don't need the fully resolved unit, check for the cached result.
if (!withUnit) {
- FileState file = _fsState.getFile(path);
+ FileState file = _fsState.getFileForPath(path);
// Prepare the key for the cached result.
String key = _getResolvedUnitKey(file);
if (key == null) {
@@ -534,14 +556,13 @@
// Append the defining unit.
{
UnlinkedUnit unlinked = libraryFile.unlinked;
- _addToStoreUnlinked(store, libraryUriStr, unlinked);
+ _addToStoreUnlinked(store, libraryFile.uri, unlinked);
}
// Append parts.
for (FileState part in libraryFile.partedFiles) {
- String partUriStr = part.uri.toString();
UnlinkedUnit unlinked = part.unlinked;
- _addToStoreUnlinked(store, partUriStr, unlinked);
+ _addToStoreUnlinked(store, part.uri, unlinked);
}
// Create nodes for referenced libraries.
@@ -565,7 +586,7 @@
if (bytes != null) {
PackageBundle linked = new PackageBundle.fromBuffer(bytes);
_addToStoreLinked(
- store, node.uri.toString(), linked.linkedLibraries.single);
+ store, node.file.uri.toString(), linked.linkedLibraries.single);
} else {
libraryUrisToLink.add(node.uri.toString());
}
@@ -578,15 +599,9 @@
_logger.run('Link bundles', () {
linkedLibraries = link(libraryUrisToLink, (String uri) {
LinkedLibrary linkedLibrary = store.linkedMap[uri];
- if (linkedLibrary == null) {
- throw new StateError('No linked library for: $uri');
- }
return linkedLibrary;
}, (String uri) {
UnlinkedUnit unlinkedUnit = store.unlinkedMap[uri];
- if (unlinkedUnit == null) {
- throw new StateError('No unlinked unit for: $uri');
- }
return unlinkedUnit;
}, (_) => null, _analysisOptions.strongMode);
_logger.writeln('Linked ${linkedLibraries.length} bundles.');
@@ -688,14 +703,20 @@
*/
FileState _verifyApiSignature(String path) {
return _logger.run('Verify API signature of $path', () {
- FileState file = _fsState.getFile(path);
- bool apiChanged = file.refresh();
- if (apiChanged) {
+ bool anyApiChanged = false;
+ List<FileState> files = _fsState.getFilesForPath(path);
+ for (FileState file in files) {
+ bool apiChanged = file.refresh();
+ if (apiChanged) {
+ anyApiChanged = true;
+ }
+ }
+ if (anyApiChanged) {
_logger.writeln('API signatures mismatch found for $path');
_dependencySignatureMap.clear();
_filesToAnalyze.addAll(_explicitFiles);
}
- return file;
+ return files[0];
});
}
@@ -796,6 +817,53 @@
}
/**
+ * The result of parsing of a single file.
+ *
+ * These results are self-consistent, i.e. [content], [contentHash], the
+ * resolved [unit] correspond to each other. But none of the results is
+ * guaranteed to be consistent with the state of the files.
+ */
+class ParseResult {
+ /**
+ * The path of the parsed file, absolute and normalized.
+ */
+ final String path;
+
+ /**
+ * The URI of the file that corresponded to the [path].
+ */
+ final Uri uri;
+
+ /**
+ * The content of the file that was scanned and parsed.
+ */
+ final String content;
+
+ /**
+ * The MD5 hash of the [content].
+ */
+ final String contentHash;
+
+ /**
+ * Information about lines in the [content].
+ */
+ final LineInfo lineInfo;
+
+ /**
+ * The parsed, unresolved compilation unit for the [content].
+ */
+ final CompilationUnit unit;
+
+ /**
+ * The scanning and parsing errors.
+ */
+ final List<AnalysisError> errors;
+
+ ParseResult(this.path, this.uri, this.content, this.contentHash,
+ this.lineInfo, this.unit, this.errors);
+}
+
+/**
* This class is used to gather and print performance information.
*/
class PerformanceLog {
diff --git a/pkg/analyzer/lib/src/dart/analysis/file_state.dart b/pkg/analyzer/lib/src/dart/analysis/file_state.dart
index 5ca64c5..3df2b1a 100644
--- a/pkg/analyzer/lib/src/dart/analysis/file_state.dart
+++ b/pkg/analyzer/lib/src/dart/analysis/file_state.dart
@@ -76,7 +76,10 @@
*/
final Uri uri;
- Source _source;
+ /**
+ * The [Source] of the file with the [uri].
+ */
+ Source source;
String _content;
String _contentHash;
@@ -89,9 +92,7 @@
List<FileState> _partedFiles;
List<FileState> _dependencies;
- FileState(this._fsState, this.path, this.uri) {
- _source = new FileSource(_fsState._resourceProvider.getFile(path), uri);
- }
+ FileState._(this._fsState, this.path, this.uri, this.source);
/**
* The unlinked API signature of the file.
@@ -109,11 +110,6 @@
String get contentHash => _contentHash;
/**
- * Return information about line in the file.
- */
- LineInfo get lineInfo => _lineInfo;
-
- /**
* Return the list of all direct dependencies.
*/
List<FileState> get dependencies => _dependencies;
@@ -123,26 +119,53 @@
*/
List<FileState> get exportedFiles => _exportedFiles;
+ @override
+ int get hashCode => uri.hashCode;
+
/**
* The list of files this file imports.
*/
List<FileState> get importedFiles => _importedFiles;
/**
+ * Return information about line in the file.
+ */
+ LineInfo get lineInfo => _lineInfo;
+
+ /**
* The list of files this library file references as parts.
*/
List<FileState> get partedFiles => _partedFiles;
/**
- * The [Source] of the file in the [SourceFactory].
- */
- Source get source => _source;
-
- /**
* The [UnlinkedUnit] of the file.
*/
UnlinkedUnit get unlinked => _unlinked;
+ @override
+ bool operator ==(Object other) {
+ return other is FileState && other.uri == uri;
+ }
+
+ /**
+ * Return a new parsed unresolved [CompilationUnit].
+ */
+ CompilationUnit parse(AnalysisErrorListener errorListener) {
+ AnalysisOptions analysisOptions = _fsState._analysisOptions;
+
+ CharSequenceReader reader = new CharSequenceReader(content);
+ Scanner scanner = new Scanner(source, reader, errorListener);
+ scanner.scanGenericMethodComments = analysisOptions.strongMode;
+ Token token = scanner.tokenize();
+ LineInfo lineInfo = new LineInfo(scanner.lineStarts);
+
+ Parser parser = new Parser(source, errorListener);
+ parser.parseGenericMethodComments = analysisOptions.strongMode;
+ CompilationUnit unit = parser.parseCompilationUnit(token);
+ unit.lineInfo = lineInfo;
+ return unit;
+ }
+
/**
* Read the file content and ensure that all of the file properties are
* consistent with the read content, including API signature.
@@ -186,8 +209,7 @@
{
bytes = _fsState._byteStore.get(unlinkedKey);
if (bytes == null) {
- CompilationUnit unit =
- _parse(_source, _content, _fsState._analysisOptions);
+ CompilationUnit unit = parse(AnalysisErrorListener.NULL_LISTENER);
_fsState._logger.run('Create unlinked for $path', () {
UnlinkedUnitBuilder unlinkedUnit = serializeAstUnlinked(unit);
bytes = unlinkedUnit.toBuffer();
@@ -213,7 +235,9 @@
String uri = import.uri;
if (!_isDartUri(uri)) {
FileState file = _fileForRelativeUri(uri);
- _importedFiles.add(file);
+ if (file != null) {
+ _importedFiles.add(file);
+ }
}
}
}
@@ -221,13 +245,17 @@
String uri = export.uri;
if (!_isDartUri(uri)) {
FileState file = _fileForRelativeUri(uri);
- _exportedFiles.add(file);
+ if (file != null) {
+ _exportedFiles.add(file);
+ }
}
}
for (String uri in _unlinked.publicNamespace.parts) {
if (!_isDartUri(uri)) {
FileState file = _fileForRelativeUri(uri);
- _partedFiles.add(file);
+ if (file != null) {
+ _partedFiles.add(file);
+ }
}
}
@@ -250,10 +278,7 @@
*/
FileState _fileForRelativeUri(String relativeUri) {
Uri absoluteUri = resolveRelativeUri(uri, FastUri.parse(relativeUri));
- String absolutePath = _fsState._sourceFactory
- .resolveUri(null, absoluteUri.toString())
- .fullName;
- return _fsState.getFile(absolutePath, absoluteUri);
+ return _fsState.getFileForUri(absoluteUri);
}
/**
@@ -279,26 +304,6 @@
static bool _isDartUri(String uri) {
return uri.startsWith('dart:');
}
-
- /**
- * Return the parsed unresolved [CompilationUnit] for the given [content].
- */
- static CompilationUnit _parse(
- Source source, String content, AnalysisOptions analysisOptions) {
- AnalysisErrorListener errorListener = AnalysisErrorListener.NULL_LISTENER;
-
- CharSequenceReader reader = new CharSequenceReader(content);
- Scanner scanner = new Scanner(source, reader, errorListener);
- scanner.scanGenericMethodComments = analysisOptions.strongMode;
- Token token = scanner.tokenize();
- LineInfo lineInfo = new LineInfo(scanner.lineStarts);
-
- Parser parser = new Parser(source, errorListener);
- parser.parseGenericMethodComments = analysisOptions.strongMode;
- CompilationUnit unit = parser.parseCompilationUnit(token);
- unit.lineInfo = lineInfo;
- return unit;
- }
}
/**
@@ -313,7 +318,20 @@
final AnalysisOptions _analysisOptions;
final Uint32List _salt;
- final Map<String, FileState> _pathToFile = <String, FileState>{};
+ /**
+ * Mapping from a URI to the corresponding [FileState].
+ */
+ final Map<Uri, FileState> _uriToFile = {};
+
+ /**
+ * Mapping from a path to the corresponding [FileState]s, canonical or not.
+ */
+ final Map<String, List<FileState>> _pathToFiles = {};
+
+ /**
+ * Mapping from a path to the corresponding canonical [FileState].
+ */
+ final Map<String, FileState> _pathToCanonicalFile = {};
FileSystemState(
this._logger,
@@ -325,25 +343,73 @@
this._salt);
/**
- * Return the [FileState] for the give [path]. The returned file has the
- * last known state since if was last refreshed.
+ * Return the canonical [FileState] for the given absolute [path]. The
+ * returned file has the last known state since if was last refreshed.
+ *
+ * Here "canonical" means that if the [path] is in a package `lib` then the
+ * returned file will have the `package:` style URI.
*/
- FileState getFile(String path, [Uri uri]) {
- FileState file = _pathToFile[path];
+ FileState getFileForPath(String path) {
+ FileState file = _pathToCanonicalFile[path];
if (file == null) {
- uri ??= _uriForPath(path);
- file = new FileState(this, path, uri);
- _pathToFile[path] = file;
+ File resource = _resourceProvider.getFile(path);
+ Source fileSource = resource.createSource();
+ Uri uri = _sourceFactory.restoreUri(fileSource);
+ // Try to get the existing instance.
+ file = _uriToFile[uri];
+ // If we have a file, call it the canonical one and return it.
+ if (file != null) {
+ _pathToCanonicalFile[path] = file;
+ return file;
+ }
+ // Create a new file.
+ FileSource uriSource = new FileSource(resource, uri);
+ file = new FileState._(this, path, uri, uriSource);
+ _uriToFile[uri] = file;
+ _pathToFiles.putIfAbsent(path, () => <FileState>[]).add(file);
+ _pathToCanonicalFile[path] = file;
file.refresh();
}
return file;
}
/**
- * Return the default [Uri] for the given path in [_sourceFactory].
+ * Return the [FileState] for the given absolute [uri]. May return `null` if
+ * the [uri] is invalid, e.g. a `package:` URI without a package name. The
+ * returned file has the last known state since if was last refreshed.
*/
- Uri _uriForPath(String path) {
- Source fileSource = _resourceProvider.getFile(path).createSource();
- return _sourceFactory.restoreUri(fileSource);
+ FileState getFileForUri(Uri uri) {
+ FileState file = _uriToFile[uri];
+ if (file == null) {
+ Source uriSource = _sourceFactory.resolveUri(null, uri.toString());
+ // If the URI is invalid, for example package:/test/d.dart (note the
+ // leading '/'), then `null` is returned. We should ignore this URI.
+ if (uriSource == null) {
+ return null;
+ }
+ String path = uriSource.fullName;
+ File resource = _resourceProvider.getFile(path);
+ FileSource source = new FileSource(resource, uri);
+ file = new FileState._(this, path, uri, source);
+ _uriToFile[uri] = file;
+ _pathToFiles.putIfAbsent(path, () => <FileState>[]).add(file);
+ file.refresh();
+ }
+ return file;
+ }
+
+ /**
+ * Return the list of all [FileState]s corresponding to the given [path]. The
+ * list has at least one item, and the first item is the canonical file.
+ */
+ List<FileState> getFilesForPath(String path) {
+ FileState canonicalFile = getFileForPath(path);
+ List<FileState> allFiles = _pathToFiles[path].toList();
+ if (allFiles.length == 1) {
+ return allFiles;
+ }
+ return allFiles
+ ..remove(canonicalFile)
+ ..insert(0, canonicalFile);
}
}
diff --git a/pkg/analyzer/lib/src/dart/element/element.dart b/pkg/analyzer/lib/src/dart/element/element.dart
index 3f7545e..3e29c82 100644
--- a/pkg/analyzer/lib/src/dart/element/element.dart
+++ b/pkg/analyzer/lib/src/dart/element/element.dart
@@ -3581,7 +3581,12 @@
List<TypeParameterElement> _typeParameters;
/**
- * The return type defined by this executable element.
+ * The declared return type of this executable element.
+ */
+ DartType _declaredReturnType;
+
+ /**
+ * The inferred return type of this executable element.
*/
DartType _returnType;
@@ -3636,6 +3641,11 @@
return super.codeOffset;
}
+ void set declaredReturnType(DartType returnType) {
+ _assertNotResynthesized(serializedExecutable);
+ _declaredReturnType = returnType;
+ }
+
@override
String get displayName {
if (serializedExecutable != null) {
@@ -3847,17 +3857,18 @@
@override
DartType get returnType {
- if (serializedExecutable != null && _returnType == null) {
+ if (serializedExecutable != null &&
+ _declaredReturnType == null &&
+ _returnType == null) {
bool isSetter =
serializedExecutable.kind == UnlinkedExecutableKind.setter;
_returnType = enclosingUnit.resynthesizerContext.resolveLinkedType(
- serializedExecutable.inferredReturnTypeSlot,
- typeParameterContext) ??
- enclosingUnit.resynthesizerContext.resolveTypeRef(
- serializedExecutable.returnType, typeParameterContext,
- defaultVoid: isSetter && context.analysisOptions.strongMode);
+ serializedExecutable.inferredReturnTypeSlot, typeParameterContext);
+ _declaredReturnType = enclosingUnit.resynthesizerContext.resolveTypeRef(
+ serializedExecutable.returnType, typeParameterContext,
+ defaultVoid: isSetter && context.analysisOptions.strongMode);
}
- return _returnType;
+ return _returnType ?? _declaredReturnType;
}
void set returnType(DartType returnType) {
@@ -6770,11 +6781,11 @@
@override
DartType get type {
- if (_unlinkedVariable != null && _type == null) {
+ if (_unlinkedVariable != null && _declaredType == null && _type == null) {
_type = enclosingUnit.resynthesizerContext.resolveLinkedType(
- _unlinkedVariable.inferredTypeSlot, typeParameterContext) ??
- enclosingUnit.resynthesizerContext
- .resolveTypeRef(_unlinkedVariable.type, typeParameterContext);
+ _unlinkedVariable.inferredTypeSlot, typeParameterContext);
+ _declaredType = enclosingUnit.resynthesizerContext
+ .resolveTypeRef(_unlinkedVariable.type, typeParameterContext);
}
return super.type;
}
@@ -7214,7 +7225,7 @@
* been build yet, build them and remember in the corresponding fields.
*/
void _resynthesizeTypeAndParameters() {
- if (_unlinkedParam != null && _type == null) {
+ if (_unlinkedParam != null && _declaredType == null && _type == null) {
if (_unlinkedParam.isFunctionTyped) {
CompilationUnitElementImpl enclosingUnit = this.enclosingUnit;
FunctionElementImpl parameterTypeElement =
@@ -7241,9 +7252,9 @@
_type = parameterType;
} else {
_type = enclosingUnit.resynthesizerContext.resolveLinkedType(
- _unlinkedParam.inferredTypeSlot, typeParameterContext) ??
- enclosingUnit.resynthesizerContext
- .resolveTypeRef(_unlinkedParam.type, typeParameterContext);
+ _unlinkedParam.inferredTypeSlot, typeParameterContext);
+ _declaredType = enclosingUnit.resynthesizerContext
+ .resolveTypeRef(_unlinkedParam.type, typeParameterContext);
}
}
}
@@ -8302,6 +8313,11 @@
/**
* The declared type of this variable.
*/
+ DartType _declaredType;
+
+ /**
+ * The inferred type of this variable.
+ */
DartType _type;
/**
@@ -8348,6 +8364,10 @@
@override
DartObject get constantValue => evaluationResult?.value;
+ void set declaredType(DartType type) {
+ _declaredType = type;
+ }
+
@override
String get displayName => name;
@@ -8421,7 +8441,7 @@
bool get isStatic => hasModifier(Modifier.STATIC);
@override
- DartType get type => _type;
+ DartType get type => _type ?? _declaredType;
void set type(DartType type) {
_type = type;
diff --git a/pkg/analyzer/lib/src/error/codes.dart b/pkg/analyzer/lib/src/error/codes.dart
index 140c658..48702e6 100644
--- a/pkg/analyzer/lib/src/error/codes.dart
+++ b/pkg/analyzer/lib/src/error/codes.dart
@@ -4651,10 +4651,12 @@
*/
class StrongModeCode extends ErrorCode {
static const String _implicitCastMessage =
- "Unsound implicit cast from '{0}' to '{1}'.";
+ "Unsafe implicit cast from '{0}' to '{1}'. "
+ "This usually indicates that type information was lost and resulted in "
+ "'dynamic' and/or a place that will have a failure at runtime.";
static const String _implicitCastCorrection =
- "Try adding an explicit cast to '{1}'.";
+ "Try adding an explicit cast to '{1}' or improving the type of '{0}'.";
static const String _invalidOverrideMessage =
"The type of '{0}.{1}' ('{2}') isn't a subtype of '{3}.{1}' ('{4}').";
@@ -4725,10 +4727,50 @@
static const StrongModeCode INFERRED_TYPE_CLOSURE = const StrongModeCode(
ErrorType.HINT, 'INFERRED_TYPE_CLOSURE', _inferredTypeMessage);
- static const StrongModeCode STATIC_TYPE_ERROR = const StrongModeCode(
+ static const StrongModeCode INVALID_CAST_LITERAL = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
- 'STATIC_TYPE_ERROR',
- "Type check failed: '{0}' ('{1}') isn't of type '{2}'.");
+ 'INVALID_CAST_LITERAL',
+ "The literal '{0}' with type '{1}' isn't of expected type '{2}'.");
+
+ static const StrongModeCode INVALID_CAST_LITERAL_LIST = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_CAST_LITERAL_LIST',
+ "The list literal type '{0}' isn't of expected type '{1}'. The list's "
+ "type can be changed with an explicit generic type argument or by "
+ "changing the element types.");
+
+ static const StrongModeCode INVALID_CAST_LITERAL_MAP = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_CAST_LITERAL_MAP',
+ "The map literal type '{0}' isn't of expected type '{1}'. The maps's "
+ "type can be changed with an explicit generic type arguments or by "
+ "changing the key and value types.");
+
+ static const StrongModeCode INVALID_CAST_FUNCTION_EXPR = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_CAST_FUNCTION_EXPR',
+ "The function expression type '{0}' isn't of type '{1}'. "
+ "This means its parameter or return type does not match what is "
+ "expected. Consider changing parameter type(s) or the returned type(s).");
+
+ static const StrongModeCode INVALID_CAST_NEW_EXPR = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_CAST_NEW_EXPR',
+ "The constructor returns type '{0}' that isn't of expected type '{1}'.");
+
+ static const StrongModeCode INVALID_CAST_METHOD = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_CAST_METHOD',
+ "The method tear-off '{0}' has type '{1}' that isn't of expected type "
+ "'{2}'. This means its parameter or return type does not match what is "
+ "expected.");
+
+ static const StrongModeCode INVALID_CAST_FUNCTION = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_CAST_FUNCTION',
+ "The function '{0}' has type '{1}' that isn't of expected type "
+ "'{2}'. This means its parameter or return type does not match what is "
+ "expected.");
static const StrongModeCode INVALID_SUPER_INVOCATION = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
diff --git a/pkg/analyzer/lib/src/generated/parser.dart b/pkg/analyzer/lib/src/generated/parser.dart
index 4430e76..e325da2 100644
--- a/pkg/analyzer/lib/src/generated/parser.dart
+++ b/pkg/analyzer/lib/src/generated/parser.dart
@@ -2799,6 +2799,7 @@
if (kind == ParameterKind.REQUIRED) {
_reportErrorForNode(
ParserErrorCode.POSITIONAL_PARAMETER_OUTSIDE_GROUP, parameter);
+ kind = ParameterKind.POSITIONAL;
}
return new DefaultFormalParameter(
parameter, kind, separator, defaultValue);
@@ -2812,6 +2813,7 @@
} else if (kind == ParameterKind.REQUIRED) {
_reportErrorForNode(
ParserErrorCode.NAMED_PARAMETER_OUTSIDE_GROUP, parameter);
+ kind = ParameterKind.NAMED;
}
return new DefaultFormalParameter(
parameter, kind, separator, defaultValue);
diff --git a/pkg/analyzer/lib/src/generated/resolver.dart b/pkg/analyzer/lib/src/generated/resolver.dart
index b885240..9941049 100644
--- a/pkg/analyzer/lib/src/generated/resolver.dart
+++ b/pkg/analyzer/lib/src/generated/resolver.dart
@@ -9529,7 +9529,7 @@
_recordType(exception, exceptionType);
Element element = exception.staticElement;
if (element is VariableElementImpl) {
- element.type = exceptionType;
+ element.declaredType = exceptionType;
} else {
// TODO(brianwilkerson) Report the internal error
}
@@ -9539,7 +9539,7 @@
_recordType(stackTrace, typeProvider.stackTraceType);
Element element = stackTrace.staticElement;
if (element is VariableElementImpl) {
- element.type = typeProvider.stackTraceType;
+ element.declaredType = typeProvider.stackTraceType;
} else {
// TODO(brianwilkerson) Report the internal error
}
@@ -9665,7 +9665,7 @@
declaredType = _typeNameResolver._getType(typeName);
}
LocalVariableElementImpl element = node.element as LocalVariableElementImpl;
- element.type = declaredType;
+ element.declaredType = declaredType;
return null;
}
@@ -9688,7 +9688,7 @@
} else {
type = _typeNameResolver._getType(typeName);
}
- element.type = type ?? _dynamicType;
+ element.declaredType = type ?? _dynamicType;
} else {
_setFunctionTypedParameterType(element, node.type, node.parameters);
}
@@ -9712,7 +9712,7 @@
AnalysisEngine.instance.logger.logError(buffer.toString(),
new CaughtException(new AnalysisException(), null));
}
- element.returnType = _computeReturnType(node.returnType);
+ element.declaredReturnType = _computeReturnType(node.returnType);
element.type = new FunctionTypeImpl(element);
_inferSetterReturnType(element);
return null;
@@ -9761,7 +9761,7 @@
AnalysisEngine.instance.logger.logError(buffer.toString(),
new CaughtException(new AnalysisException(), null));
}
- element.returnType = _computeReturnType(node.returnType);
+ element.declaredReturnType = _computeReturnType(node.returnType);
element.type = new FunctionTypeImpl(element);
_inferSetterReturnType(element);
if (element is PropertyAccessorElement) {
@@ -9769,11 +9769,11 @@
PropertyInducingElementImpl variable =
accessor.variable as PropertyInducingElementImpl;
if (accessor.isGetter) {
- variable.type = element.returnType;
+ variable.declaredType = element.returnType;
} else if (variable.type == null) {
List<ParameterElement> parameters = element.parameters;
if (parameters != null && parameters.length > 0) {
- variable.type = parameters[0].type;
+ variable.declaredType = parameters[0].type;
}
}
}
@@ -9898,7 +9898,7 @@
}
Element element = node.identifier.staticElement;
if (element is ParameterElementImpl) {
- element.type = declaredType;
+ element.declaredType = declaredType;
} else {
// TODO(brianwilkerson) Report the internal error.
}
@@ -9963,7 +9963,7 @@
}
Element element = node.name.staticElement;
if (element is VariableElementImpl) {
- element.type = declaredType;
+ element.declaredType = declaredType;
}
return null;
}
@@ -10037,7 +10037,7 @@
element is PropertyAccessorElementImpl &&
element.isSetter &&
element.hasImplicitReturnType) {
- element.returnType = VoidTypeImpl.instance;
+ element.declaredReturnType = VoidTypeImpl.instance;
}
}
@@ -10185,7 +10185,7 @@
FunctionElementImpl functionElement = new FunctionElementImpl.forNode(null);
functionElement.synthetic = true;
functionElement.shareParameters(parameters);
- functionElement.returnType = _computeReturnType(returnType);
+ functionElement.declaredReturnType = _computeReturnType(returnType);
functionElement.enclosingElement = element;
functionElement.shareTypeParameters(element.typeParameters);
element.type = new FunctionTypeImpl(functionElement);
diff --git a/pkg/analyzer/lib/src/summary/api_signature.dart b/pkg/analyzer/lib/src/summary/api_signature.dart
index 230b6d0..d8c29c6 100644
--- a/pkg/analyzer/lib/src/summary/api_signature.dart
+++ b/pkg/analyzer/lib/src/summary/api_signature.dart
@@ -72,10 +72,12 @@
* `addBytes([1]); addBytes([2]);`.
*/
void addBytes(List<int> bytes) {
- _makeRoom(bytes.length);
- new Uint8List.view(_data.buffer)
- .setRange(_offset, _offset + bytes.length, bytes);
- _offset += bytes.length;
+ int length = bytes.length;
+ _makeRoom(length);
+ for (int i = 0; i < length; i++) {
+ _data.setUint8(_offset + i, bytes[i]);
+ }
+ _offset += length;
}
/**
diff --git a/pkg/analyzer/lib/src/task/strong/checker.dart b/pkg/analyzer/lib/src/task/strong/checker.dart
index b32ff6e..4e2a092 100644
--- a/pkg/analyzer/lib/src/task/strong/checker.dart
+++ b/pkg/analyzer/lib/src/task/strong/checker.dart
@@ -1051,10 +1051,25 @@
assert(rules.isSubtypeOf(to, from));
// Inference "casts":
- if (expr is Literal || expr is FunctionExpression) {
+ if (expr is Literal) {
// fromT should be an exact type - this will almost certainly fail at
// runtime.
- _recordMessage(expr, StrongModeCode.STATIC_TYPE_ERROR, [expr, from, to]);
+ if (expr is ListLiteral) {
+ _recordMessage(
+ expr, StrongModeCode.INVALID_CAST_LITERAL_LIST, [from, to]);
+ } else if (expr is MapLiteral) {
+ _recordMessage(
+ expr, StrongModeCode.INVALID_CAST_LITERAL_MAP, [from, to]);
+ } else {
+ _recordMessage(
+ expr, StrongModeCode.INVALID_CAST_LITERAL, [expr, from, to]);
+ }
+ return;
+ }
+
+ if (expr is FunctionExpression) {
+ _recordMessage(
+ expr, StrongModeCode.INVALID_CAST_FUNCTION_EXPR, [from, to]);
return;
}
@@ -1063,15 +1078,19 @@
if (e == null || !e.isFactory) {
// fromT should be an exact type - this will almost certainly fail at
// runtime.
-
- _recordMessage(
- expr, StrongModeCode.STATIC_TYPE_ERROR, [expr, from, to]);
+ _recordMessage(expr, StrongModeCode.INVALID_CAST_NEW_EXPR, [from, to]);
return;
}
}
if (isKnownFunction(expr)) {
- _recordMessage(expr, StrongModeCode.STATIC_TYPE_ERROR, [expr, from, to]);
+ Element e = _getKnownElement(expr);
+ _recordMessage(
+ expr,
+ e is MethodElement
+ ? StrongModeCode.INVALID_CAST_METHOD
+ : StrongModeCode.INVALID_CAST_FUNCTION,
+ [e.name, from, to]);
return;
}
@@ -1088,7 +1107,7 @@
downCastComposite =
typeArgs.isEmpty || typeArgs.any((t) => t.isDynamic);
} else {
- downCastComposite = true;
+ downCastComposite = !from.isDynamic;
}
}
diff --git a/pkg/analyzer/test/generated/parser_test.dart b/pkg/analyzer/test/generated/parser_test.dart
index e4b714c..a7638b8 100644
--- a/pkg/analyzer/test/generated/parser_test.dart
+++ b/pkg/analyzer/test/generated/parser_test.dart
@@ -2166,6 +2166,8 @@
expectNotNullIfNoErrors(list);
listener
.assertErrorsWithCodes([ParserErrorCode.NAMED_PARAMETER_OUTSIDE_GROUP]);
+ expect(list.parameters[0].kind, ParameterKind.REQUIRED);
+ expect(list.parameters[1].kind, ParameterKind.NAMED);
}
void test_nonConstructorFactory_field() {
@@ -2292,6 +2294,8 @@
expectNotNullIfNoErrors(list);
listener.assertErrorsWithCodes(
[ParserErrorCode.POSITIONAL_PARAMETER_OUTSIDE_GROUP]);
+ expect(list.parameters[0].kind, ParameterKind.REQUIRED);
+ expect(list.parameters[1].kind, ParameterKind.POSITIONAL);
}
void test_redirectingConstructorWithBody_named() {
diff --git a/pkg/analyzer/test/src/context/context_test.dart b/pkg/analyzer/test/src/context/context_test.dart
index 7c6c668..54f5619 100644
--- a/pkg/analyzer/test/src/context/context_test.dart
+++ b/pkg/analyzer/test/src/context/context_test.dart
@@ -1163,6 +1163,125 @@
expect(unit, isNotNull);
}
+ void test_flushSingleResolvedUnit_instanceField() {
+ _checkFlushSingleResolvedUnit('class C { var x = 0; }',
+ (CompilationUnitElement unitElement, String reason) {
+ expect(unitElement.types, hasLength(1), reason: reason);
+ ClassElement cls = unitElement.types[0];
+ expect(cls.fields, hasLength(1), reason: reason);
+ expect(cls.fields[0].type.toString(), 'int', reason: reason);
+ expect(cls.accessors, hasLength(2), reason: reason);
+ expect(cls.accessors[0].isGetter, isTrue, reason: reason);
+ expect(cls.accessors[0].returnType.toString(), 'int', reason: reason);
+ expect(cls.accessors[1].isSetter, isTrue, reason: reason);
+ expect(cls.accessors[1].returnType.toString(), 'void', reason: reason);
+ expect(cls.accessors[1].parameters, hasLength(1), reason: reason);
+ expect(cls.accessors[1].parameters[0].type.toString(), 'int',
+ reason: reason);
+ });
+ }
+
+ void test_flushSingleResolvedUnit_instanceGetter() {
+ _checkFlushSingleResolvedUnit(
+ '''
+abstract class B {
+ int get x;
+}
+class C extends B {
+ get x => null;
+}
+''', (CompilationUnitElement unitElement, String reason) {
+ expect(unitElement.types, hasLength(2), reason: reason);
+ ClassElement cls = unitElement.types[1];
+ expect(cls.name, 'C', reason: reason);
+ expect(cls.accessors, hasLength(1), reason: reason);
+ expect(cls.accessors[0].returnType.toString(), 'int', reason: reason);
+ expect(cls.fields, hasLength(1), reason: reason);
+ expect(cls.fields[0].type.toString(), 'int', reason: reason);
+ });
+ }
+
+ void test_flushSingleResolvedUnit_instanceMethod() {
+ _checkFlushSingleResolvedUnit(
+ '''
+abstract class B {
+ int f(String s);
+}
+class C extends B {
+ f(s) => null;
+}
+''', (CompilationUnitElement unitElement, String reason) {
+ expect(unitElement.types, hasLength(2), reason: reason);
+ ClassElement cls = unitElement.types[1];
+ expect(cls.name, 'C', reason: reason);
+ expect(cls.methods, hasLength(1), reason: reason);
+ expect(cls.methods[0].returnType.toString(), 'int', reason: reason);
+ expect(cls.methods[0].parameters, hasLength(1), reason: reason);
+ expect(cls.methods[0].parameters[0].type.toString(), 'String',
+ reason: reason);
+ });
+ }
+
+ void test_flushSingleResolvedUnit_instanceSetter() {
+ _checkFlushSingleResolvedUnit(
+ '''
+abstract class B {
+ set x(int value);
+}
+class C extends B {
+ set x(value) {}
+}
+''', (CompilationUnitElement unitElement, String reason) {
+ expect(unitElement.types, hasLength(2), reason: reason);
+ ClassElement cls = unitElement.types[1];
+ expect(cls.name, 'C', reason: reason);
+ expect(cls.accessors, hasLength(1), reason: reason);
+ expect(cls.accessors[0].returnType.toString(), 'void', reason: reason);
+ expect(cls.accessors[0].parameters, hasLength(1), reason: reason);
+ expect(cls.accessors[0].parameters[0].type.toString(), 'int',
+ reason: reason);
+ expect(cls.fields, hasLength(1), reason: reason);
+ expect(cls.fields[0].type.toString(), 'int', reason: reason);
+ });
+ }
+
+ void test_flushSingleResolvedUnit_staticField() {
+ _checkFlushSingleResolvedUnit('class C { static var x = 0; }',
+ (CompilationUnitElement unitElement, String reason) {
+ expect(unitElement.types, hasLength(1), reason: reason);
+ ClassElement cls = unitElement.types[0];
+ expect(cls.fields, hasLength(1), reason: reason);
+ expect(cls.fields[0].type.toString(), 'int', reason: reason);
+ expect(cls.accessors, hasLength(2), reason: reason);
+ expect(cls.accessors[0].isGetter, isTrue, reason: reason);
+ expect(cls.accessors[0].returnType.toString(), 'int', reason: reason);
+ expect(cls.accessors[1].isSetter, isTrue, reason: reason);
+ expect(cls.accessors[1].returnType.toString(), 'void', reason: reason);
+ expect(cls.accessors[1].parameters, hasLength(1), reason: reason);
+ expect(cls.accessors[1].parameters[0].type.toString(), 'int',
+ reason: reason);
+ });
+ }
+
+ void test_flushSingleResolvedUnit_topLevelVariable() {
+ _checkFlushSingleResolvedUnit('var x = 0;',
+ (CompilationUnitElement unitElement, String reason) {
+ expect(unitElement.topLevelVariables, hasLength(1), reason: reason);
+ expect(unitElement.topLevelVariables[0].type.toString(), 'int',
+ reason: reason);
+ expect(unitElement.accessors, hasLength(2), reason: reason);
+ expect(unitElement.accessors[0].isGetter, isTrue, reason: reason);
+ expect(unitElement.accessors[0].returnType.toString(), 'int',
+ reason: reason);
+ expect(unitElement.accessors[1].isSetter, isTrue, reason: reason);
+ expect(unitElement.accessors[1].returnType.toString(), 'void',
+ reason: reason);
+ expect(unitElement.accessors[1].parameters, hasLength(1), reason: reason);
+ expect(unitElement.accessors[1].parameters[0].type.toString(), 'int',
+ reason: reason);
+ });
+ }
+
void test_getAnalysisOptions() {
expect(context.analysisOptions, isNotNull);
}
@@ -2529,6 +2648,15 @@
assertNamedElements(importedLibraries, ["dart.core", "libB"]);
}
+ void test_resolveCompilationUnit_library() {
+ Source source = addSource("/lib.dart", "library lib;");
+ LibraryElement library = context.computeLibraryElement(source);
+ CompilationUnit compilationUnit =
+ context.resolveCompilationUnit(source, library);
+ expect(compilationUnit, isNotNull);
+ expect(compilationUnit.element, isNotNull);
+ }
+
// void test_resolveCompilationUnit_sourceChangeDuringResolution() {
// _context = new _AnalysisContext_sourceChangeDuringResolution();
// AnalysisContextFactory.initContextWithCore(_context);
@@ -2540,15 +2668,6 @@
// expect(_context.getLineInfo(source), isNotNull);
// }
- void test_resolveCompilationUnit_library() {
- Source source = addSource("/lib.dart", "library lib;");
- LibraryElement library = context.computeLibraryElement(source);
- CompilationUnit compilationUnit =
- context.resolveCompilationUnit(source, library);
- expect(compilationUnit, isNotNull);
- expect(compilationUnit.element, isNotNull);
- }
-
void test_resolveCompilationUnit_source() {
Source source = addSource("/lib.dart", "library lib;");
CompilationUnit compilationUnit =
@@ -2829,6 +2948,25 @@
context.applyChanges(changeSet);
}
+ void _checkFlushSingleResolvedUnit(String code,
+ void validate(CompilationUnitElement unitElement, String reason)) {
+ prepareAnalysisContext(new AnalysisOptionsImpl()..strongMode = true);
+ String path = resourceProvider.convertPath('/test.dart');
+ Source source = resourceProvider.newFile(path, code).createSource();
+ context.applyChanges(new ChangeSet()..addedSource(source));
+ CompilationUnitElement unitElement =
+ context.resolveCompilationUnit2(source, source).element;
+ validate(unitElement, 'initial state');
+ for (ResultDescriptor<CompilationUnit> descriptor
+ in RESOLVED_UNIT_RESULTS) {
+ context.analysisCache.flush(
+ (target, result) => target.source == source && result == descriptor);
+ context.computeResult(
+ new LibrarySpecificUnit(source, source), descriptor);
+ validate(unitElement, 'after flushing $descriptor');
+ }
+ }
+
/**
* Search the given compilation unit for a class with the given name. Return the class with the
* given name, or `null` if the class cannot be found.
diff --git a/pkg/analyzer/test/src/dart/analysis/driver_test.dart b/pkg/analyzer/test/src/dart/analysis/driver_test.dart
index dff172e..7ce9f31 100644
--- a/pkg/analyzer/test/src/dart/analysis/driver_test.dart
+++ b/pkg/analyzer/test/src/dart/analysis/driver_test.dart
@@ -8,6 +8,7 @@
import 'dart:convert';
import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/memory_file_system.dart';
@@ -75,7 +76,8 @@
new DartUriResolver(sdk),
new PackageMapUriResolver(provider, <String, List<Folder>>{
'test': [provider.getFolder(testProject)]
- })
+ }),
+ new ResourceUriResolver(provider)
], null, provider),
new AnalysisOptionsImpl()..strongMode = true);
driver.status.lastWhere((status) {
@@ -287,6 +289,94 @@
expect(_getClassFieldType(result.unit, 'C', 'f'), 'int');
}
+ test_getResult_sameFile_twoUris() async {
+ var a = _p('/test/lib/a.dart');
+ var b = _p('/test/lib/b.dart');
+ var c = _p('/test/test/c.dart');
+ provider.newFile(a, 'class A<T> {}');
+ provider.newFile(
+ b,
+ r'''
+import 'a.dart';
+var VB = new A<int>();
+''');
+ provider.newFile(
+ c,
+ r'''
+import '../lib/a.dart';
+var VC = new A<double>();
+''');
+
+ driver.addFile(a);
+ driver.addFile(b);
+ await _waitForIdle();
+
+ {
+ AnalysisResult result = await driver.getResult(b);
+ expect(_getImportSource(result.unit, 0).uri.toString(),
+ 'package:test/a.dart');
+ expect(_getTopLevelVarType(result.unit, 'VB'), 'A<int>');
+ }
+
+ {
+ AnalysisResult result = await driver.getResult(c);
+ expect(_getImportSource(result.unit, 0).uri,
+ provider.pathContext.toUri(_p('/test/lib/a.dart')));
+ expect(_getTopLevelVarType(result.unit, 'VC'), 'A<double>');
+ }
+ }
+
+ test_getResult_mix_fileAndPackageUris() async {
+ var a = _p('/test/bin/a.dart');
+ var b = _p('/test/bin/b.dart');
+ var c = _p('/test/lib/c.dart');
+ var d = _p('/test/test/d.dart');
+ provider.newFile(
+ a,
+ r'''
+import 'package:test/c.dart';
+int x = y;
+''');
+ provider.newFile(
+ b,
+ r'''
+import '../lib/c.dart';
+int x = y;
+''');
+ provider.newFile(
+ c,
+ r'''
+import '../test/d.dart';
+var y = z;
+''');
+ provider.newFile(
+ d,
+ r'''
+String z = "string";
+''');
+
+ // Analysis of my_pkg/bin/a.dart produces no error because
+ // file:///my_pkg/bin/a.dart imports package:my_pkg/c.dart, and
+ // package:my_pkg/c.dart's import is erroneous, causing y's reference to z
+ // to be unresolved (and therefore have type dynamic).
+ {
+ AnalysisResult result = await driver.getResult(a);
+ expect(result.errors, isEmpty);
+ }
+
+ // Analysis of my_pkg/bin/b.dart produces the error "A value of type
+ // 'String' can't be assigned to a variable of type 'int'", because
+ // file:///my_pkg/bin/b.dart imports file:///my_pkg/lib/c.dart, which
+ // successfully imports file:///my_pkg/test/d.dart, causing y to have an
+ // inferred type of String.
+ {
+ AnalysisResult result = await driver.getResult(b);
+ List<AnalysisError> errors = result.errors;
+ expect(errors, hasLength(1));
+ expect(errors[0].errorCode, StaticTypeWarningCode.INVALID_ASSIGNMENT);
+ }
+ }
+
test_getResult_selfConsistent() async {
var a = _p('/test/lib/a.dart');
var b = _p('/test/lib/b.dart');
@@ -549,6 +639,15 @@
return _getClassField(unit, className, fieldName).element.type.toString();
}
+ ImportElement _getImportElement(CompilationUnit unit, int directiveIndex) {
+ var import = unit.directives[directiveIndex] as ImportDirective;
+ return import.element as ImportElement;
+ }
+
+ Source _getImportSource(CompilationUnit unit, int directiveIndex) {
+ return _getImportElement(unit, directiveIndex).importedLibrary.source;
+ }
+
VariableDeclaration _getTopLevelVar(CompilationUnit unit, String name) {
for (CompilationUnitMember declaration in unit.declarations) {
if (declaration is TopLevelVariableDeclaration) {
diff --git a/pkg/analyzer/test/src/task/dart_test.dart b/pkg/analyzer/test/src/task/dart_test.dart
index b974563..428ae9c 100644
--- a/pkg/analyzer/test/src/task/dart_test.dart
+++ b/pkg/analyzer/test/src/task/dart_test.dart
@@ -5376,7 +5376,7 @@
var errors = errorListener.errors;
expect(errors.length, 1);
- expect(errors[0].errorCode.name, "STRONG_MODE_STATIC_TYPE_ERROR");
+ expect(errors[0].errorCode.name, "STRONG_MODE_INVALID_CAST_NEW_EXPR");
}
}
diff --git a/pkg/analyzer/test/src/task/strong/checker_test.dart b/pkg/analyzer/test/src/task/strong/checker_test.dart
index 48e6539..6c22865 100644
--- a/pkg/analyzer/test/src/task/strong/checker_test.dart
+++ b/pkg/analyzer/test/src/task/strong/checker_test.dart
@@ -723,7 +723,7 @@
void main() {
Cat c = /*info:ASSIGNMENT_CAST*/new Animal.cat();
- c = /*error:STATIC_TYPE_ERROR*/new Animal();
+ c = /*error:INVALID_CAST_NEW_EXPR*/new Animal();
}''');
}
@@ -988,7 +988,7 @@
baz1() async* { yield* /*info:DYNAMIC_CAST*/x; }
Stream baz2() async* { yield* /*info:DYNAMIC_CAST*/x; }
-Stream<int> baz3() async* { yield* /*warning:DOWN_CAST_COMPOSITE*/x; }
+Stream<int> baz3() async* { yield* /*info:DYNAMIC_CAST*/x; }
Stream<int> baz4() async* { yield* new Stream<int>(); }
Stream<int> baz5() async* { yield* /*info:INFERRED_TYPE_ALLOCATION*/new Stream(); }
''');
@@ -1005,7 +1005,7 @@
baz1() sync* { yield* /*info:DYNAMIC_CAST*/x; }
Iterable baz2() sync* { yield* /*info:DYNAMIC_CAST*/x; }
-Iterable<int> baz3() sync* { yield* /*warning:DOWN_CAST_COMPOSITE*/x; }
+Iterable<int> baz3() sync* { yield* /*info:DYNAMIC_CAST*/x; }
Iterable<int> baz4() sync* { yield* bar3(); }
Iterable<int> baz5() sync* { yield* /*info:INFERRED_TYPE_ALLOCATION*/new List(); }
''');
@@ -1042,23 +1042,23 @@
}
{
Left f;
- f = /*error:STATIC_TYPE_ERROR*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
f = left;
f = /*error:INVALID_ASSIGNMENT*/right;
f = bot;
}
{
Right f;
- f = /*error:STATIC_TYPE_ERROR*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
f = /*error:INVALID_ASSIGNMENT*/left;
f = right;
f = bot;
}
{
Bot f;
- f = /*error:STATIC_TYPE_ERROR*/top;
- f = /*error:STATIC_TYPE_ERROR*/left;
- f = /*error:STATIC_TYPE_ERROR*/right;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/left;
+ f = /*error:INVALID_CAST_FUNCTION*/right;
f = bot;
}
}
@@ -1226,14 +1226,14 @@
f = topA;
f = /*error:INVALID_ASSIGNMENT*/topTop;
f = aa;
- f = /*error:STATIC_TYPE_ERROR*/aTop; // known function
+ f = /*error:INVALID_CAST_FUNCTION*/aTop; // known function
f = /*warning:DOWN_CAST_COMPOSITE*/botA;
f = /*warning:DOWN_CAST_COMPOSITE*/botTop;
apply/*<AA>*/(
topA,
/*error:ARGUMENT_TYPE_NOT_ASSIGNABLE*/topTop,
aa,
- /*error:STATIC_TYPE_ERROR*/aTop, // known function
+ /*error:INVALID_CAST_FUNCTION*/aTop, // known function
/*warning:DOWN_CAST_COMPOSITE*/botA,
/*warning:DOWN_CAST_COMPOSITE*/botTop
);
@@ -1241,7 +1241,7 @@
(dynamic x) => new A(),
/*error:ARGUMENT_TYPE_NOT_ASSIGNABLE*/(dynamic x) => (x as Object),
(A x) => x,
- /*error:STATIC_TYPE_ERROR*/(A x) => (/*info:UNNECESSARY_CAST*/x as Object), // known function
+ /*error:INVALID_CAST_FUNCTION_EXPR*/(A x) => (/*info:UNNECESSARY_CAST*/x as Object), // known function
/*warning:DOWN_CAST_COMPOSITE*/botA,
/*warning:DOWN_CAST_COMPOSITE*/botTop
);
@@ -1251,14 +1251,14 @@
f = topA;
f = topTop;
f = /*error:INVALID_ASSIGNMENT*/aa;
- f = /*error:STATIC_TYPE_ERROR*/aTop; // known function
+ f = /*error:INVALID_CAST_FUNCTION*/aTop; // known function
f = /*error:INVALID_ASSIGNMENT*/botA;
f = /*warning:DOWN_CAST_COMPOSITE*/botTop;
apply/*<TopTop>*/(
topA,
topTop,
/*error:ARGUMENT_TYPE_NOT_ASSIGNABLE*/aa,
- /*error:STATIC_TYPE_ERROR*/aTop, // known function
+ /*error:INVALID_CAST_FUNCTION*/aTop, // known function
/*error:ARGUMENT_TYPE_NOT_ASSIGNABLE*/botA,
/*warning:DOWN_CAST_COMPOSITE*/botTop
);
@@ -1266,7 +1266,7 @@
(dynamic x) => new A(),
(dynamic x) => (x as Object),
/*error:ARGUMENT_TYPE_NOT_ASSIGNABLE*/(A x) => x,
- /*error:STATIC_TYPE_ERROR*/(A x) => (/*info:UNNECESSARY_CAST*/x as Object), // known function
+ /*error:INVALID_CAST_FUNCTION_EXPR*/(A x) => (/*info:UNNECESSARY_CAST*/x as Object), // known function
/*error:ARGUMENT_TYPE_NOT_ASSIGNABLE*/botA,
/*warning:DOWN_CAST_COMPOSITE*/botTop
);
@@ -1274,24 +1274,24 @@
{
TopA f;
f = topA;
- f = /*error:STATIC_TYPE_ERROR*/topTop; // known function
- f = /*error:STATIC_TYPE_ERROR*/aa; // known function
- f = /*error:STATIC_TYPE_ERROR*/aTop; // known function
+ f = /*error:INVALID_CAST_FUNCTION*/topTop; // known function
+ f = /*error:INVALID_CAST_FUNCTION*/aa; // known function
+ f = /*error:INVALID_CAST_FUNCTION*/aTop; // known function
f = /*warning:DOWN_CAST_COMPOSITE*/botA;
f = /*warning:DOWN_CAST_COMPOSITE*/botTop;
apply/*<TopA>*/(
topA,
- /*error:STATIC_TYPE_ERROR*/topTop, // known function
- /*error:STATIC_TYPE_ERROR*/aa, // known function
- /*error:STATIC_TYPE_ERROR*/aTop, // known function
+ /*error:INVALID_CAST_FUNCTION*/topTop, // known function
+ /*error:INVALID_CAST_FUNCTION*/aa, // known function
+ /*error:INVALID_CAST_FUNCTION*/aTop, // known function
/*warning:DOWN_CAST_COMPOSITE*/botA,
/*warning:DOWN_CAST_COMPOSITE*/botTop
);
apply/*<TopA>*/(
(dynamic x) => new A(),
- /*error:STATIC_TYPE_ERROR*/(dynamic x) => (x as Object), // known function
- /*error:STATIC_TYPE_ERROR*/(A x) => x, // known function
- /*error:STATIC_TYPE_ERROR*/(A x) => (/*info:UNNECESSARY_CAST*/x as Object), // known function
+ /*error:INVALID_CAST_FUNCTION_EXPR*/(dynamic x) => (x as Object), // known function
+ /*error:INVALID_CAST_FUNCTION_EXPR*/(A x) => x, // known function
+ /*error:INVALID_CAST_FUNCTION_EXPR*/(A x) => (/*info:UNNECESSARY_CAST*/x as Object), // known function
/*warning:DOWN_CAST_COMPOSITE*/botA,
/*warning:DOWN_CAST_COMPOSITE*/botTop
);
@@ -1300,7 +1300,7 @@
''');
}
- void test_functionTypingAndSubtyping_dynamicFunctions_clasuresAreNotFuzzy() {
+ void test_functionTypingAndSubtyping_dynamicFunctions_closuresAreNotFuzzy() {
// Regression test for
// https://github.com/dart-lang/sdk/issues/26118
// https://github.com/dart-lang/sdk/issues/26156
@@ -1379,23 +1379,23 @@
}
{
Function2<B, B> f; // left
- f = /*error:STATIC_TYPE_ERROR*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
f = left;
f = /*error:INVALID_ASSIGNMENT*/right;
f = bot;
}
{
Function2<A, A> f; // right
- f = /*error:STATIC_TYPE_ERROR*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
f = /*error:INVALID_ASSIGNMENT*/left;
f = right;
f = bot;
}
{
Function2<A, B> f;
- f = /*error:STATIC_TYPE_ERROR*/top;
- f = /*error:STATIC_TYPE_ERROR*/left;
- f = /*error:STATIC_TYPE_ERROR*/right;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/left;
+ f = /*error:INVALID_CAST_FUNCTION*/right;
f = bot;
}
}
@@ -1466,14 +1466,14 @@
}
{
Function2<AToB, AToB> f; // Left
- f = /*error:STATIC_TYPE_ERROR*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
f = left;
f = /*error:INVALID_ASSIGNMENT*/right;
f = bot;
}
{
Function2<BToA, BToA> f; // Right
- f = /*error:STATIC_TYPE_ERROR*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
f = /*error:INVALID_ASSIGNMENT*/left;
f = right;
f = bot;
@@ -1481,9 +1481,9 @@
{
Function2<BToA, AToB> f; // Bot
f = bot;
- f = /*error:STATIC_TYPE_ERROR*/left;
- f = /*error:STATIC_TYPE_ERROR*/top;
- f = /*error:STATIC_TYPE_ERROR*/right;
+ f = /*error:INVALID_CAST_FUNCTION*/left;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/right;
}
}
''');
@@ -1515,14 +1515,14 @@
}
{
Function2<AToB, AToB> f; // Left
- f = /*error:STATIC_TYPE_ERROR*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
f = left;
f = /*error:INVALID_ASSIGNMENT*/right;
f = bot;
}
{
Function2<BToA, BToA> f; // Right
- f = /*error:STATIC_TYPE_ERROR*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
f = /*error:INVALID_ASSIGNMENT*/left;
f = right;
f = bot;
@@ -1530,9 +1530,9 @@
{
Function2<BToA, AToB> f; // Bot
f = bot;
- f = /*error:STATIC_TYPE_ERROR*/left;
- f = /*error:STATIC_TYPE_ERROR*/top;
- f = /*error:STATIC_TYPE_ERROR*/right;
+ f = /*error:INVALID_CAST_FUNCTION*/left;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/right;
}
}
''');
@@ -1564,14 +1564,14 @@
}
{
Function2<AToB, AToB> f; // Left
- f = /*error:STATIC_TYPE_ERROR*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
f = left;
f = /*error:INVALID_ASSIGNMENT*/right;
f = bot;
}
{
Function2<BToA, BToA> f; // Right
- f = /*error:STATIC_TYPE_ERROR*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
f = /*error:INVALID_ASSIGNMENT*/left;
f = right;
f = bot;
@@ -1579,9 +1579,9 @@
{
Function2<BToA, AToB> f; // Bot
f = bot;
- f = /*error:STATIC_TYPE_ERROR*/left;
- f = /*error:STATIC_TYPE_ERROR*/top;
- f = /*error:STATIC_TYPE_ERROR*/right;
+ f = /*error:INVALID_CAST_FUNCTION*/left;
+ f = /*error:INVALID_CAST_FUNCTION*/top;
+ f = /*error:INVALID_CAST_FUNCTION*/right;
}
}
''');
@@ -1937,23 +1937,23 @@
}
{
Function2<B, B> f;
- f = /*error:STATIC_TYPE_ERROR*/C.top;
+ f = /*error:INVALID_CAST_METHOD*/C.top;
f = C.left;
f = /*error:INVALID_ASSIGNMENT*/C.right;
f = C.bot;
}
{
Function2<A, A> f;
- f = /*error:STATIC_TYPE_ERROR*/C.top;
+ f = /*error:INVALID_CAST_METHOD*/C.top;
f = /*error:INVALID_ASSIGNMENT*/C.left;
f = C.right;
f = C.bot;
}
{
Function2<A, B> f;
- f = /*error:STATIC_TYPE_ERROR*/C.top;
- f = /*error:STATIC_TYPE_ERROR*/C.left;
- f = /*error:STATIC_TYPE_ERROR*/C.right;
+ f = /*error:INVALID_CAST_METHOD*/C.top;
+ f = /*error:INVALID_CAST_METHOD*/C.left;
+ f = /*error:INVALID_CAST_METHOD*/C.right;
f = C.bot;
}
}
@@ -1984,7 +1984,7 @@
var local2 = g;
local = local2;
- local2 = /*error:STATIC_TYPE_ERROR*/f;
+ local2 = /*error:INVALID_CAST_FUNCTION*/f;
local2 = /*warning:DOWN_CAST_COMPOSITE*/local;
// Non-generic function cannot subtype a generic one.
diff --git a/pkg/analyzer/test/src/task/strong/inferred_type_test.dart b/pkg/analyzer/test/src/task/strong/inferred_type_test.dart
index b6e116a..dc4fe36 100644
--- a/pkg/analyzer/test/src/task/strong/inferred_type_test.dart
+++ b/pkg/analyzer/test/src/task/strong/inferred_type_test.dart
@@ -1232,8 +1232,8 @@
A<int, String> a1 = /*info:INFERRED_TYPE_ALLOCATION*/new A.named(3, "hello");
A<int, String> a2 = new A<int, String>(3, "hello");
A<int, String> a3 = new A<int, String>.named(3, "hello");
- A<int, String> a4 = /*error:STATIC_TYPE_ERROR*/new A<int, dynamic>(3, "hello");
- A<int, String> a5 = /*error:STATIC_TYPE_ERROR*/new A<dynamic, dynamic>.named(3, "hello");
+ A<int, String> a4 = /*error:INVALID_CAST_NEW_EXPR*/new A<int, dynamic>(3, "hello");
+ A<int, String> a5 = /*error:INVALID_CAST_NEW_EXPR*/new A<dynamic, dynamic>.named(3, "hello");
}
{
A<int, String> a0 = /*info:INFERRED_TYPE_ALLOCATION*/new /*error:COULD_NOT_INFER,error:COULD_NOT_INFER*/A(
@@ -1328,10 +1328,10 @@
List<dynamic> l3 = /*info:INFERRED_TYPE_LITERAL*/["hello", 3];
}
{
- List<int> l0 = /*error:STATIC_TYPE_ERROR*/<num>[];
- List<int> l1 = /*error:STATIC_TYPE_ERROR*/<num>[3];
- List<int> l2 = /*error:STATIC_TYPE_ERROR*/<num>[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"];
- List<int> l3 = /*error:STATIC_TYPE_ERROR*/<num>[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3];
+ List<int> l0 = /*error:INVALID_CAST_LITERAL_LIST*/<num>[];
+ List<int> l1 = /*error:INVALID_CAST_LITERAL_LIST*/<num>[3];
+ List<int> l2 = /*error:INVALID_CAST_LITERAL_LIST*/<num>[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"];
+ List<int> l3 = /*error:INVALID_CAST_LITERAL_LIST*/<num>[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3];
}
{
Iterable<int> i0 = /*info:INFERRED_TYPE_LITERAL*/[];
@@ -1465,9 +1465,9 @@
};
}
{
- Map<int, String> l0 = /*error:STATIC_TYPE_ERROR*/<num, dynamic>{};
- Map<int, String> l1 = /*error:STATIC_TYPE_ERROR*/<num, dynamic>{3: "hello"};
- Map<int, String> l3 = /*error:STATIC_TYPE_ERROR*/<num, dynamic>{3: 3};
+ Map<int, String> l0 = /*error:INVALID_CAST_LITERAL_MAP*/<num, dynamic>{};
+ Map<int, String> l1 = /*error:INVALID_CAST_LITERAL_MAP*/<num, dynamic>{3: "hello"};
+ Map<int, String> l3 = /*error:INVALID_CAST_LITERAL_MAP*/<num, dynamic>{3: 3};
}
{
const Map<int, String> l0 = /*info:INFERRED_TYPE_LITERAL*/const {};
diff --git a/pkg/compiler/lib/src/common/names.dart b/pkg/compiler/lib/src/common/names.dart
index 56d826c..06ef360 100644
--- a/pkg/compiler/lib/src/common/names.dart
+++ b/pkg/compiler/lib/src/common/names.dart
@@ -171,4 +171,13 @@
/// The URI for 'dart:_native_typed_data'.
static final Uri dart__native_typed_data =
new Uri(scheme: 'dart', path: '_native_typed_data');
+
+ /// The URI for 'dart:svg'.
+ static final Uri dart_svg = new Uri(scheme: 'dart', path: 'svg');
+
+ /// The URI for 'dart:web_audio'.
+ static final Uri dart_web_audio = new Uri(scheme: 'dart', path: 'web_audio');
+
+ /// The URI for 'dart:web_gl'.
+ static final Uri dart_web_gl = new Uri(scheme: 'dart', path: 'web_gl');
}
diff --git a/pkg/compiler/lib/src/elements/modelx.dart b/pkg/compiler/lib/src/elements/modelx.dart
index 691e6d7..b479367 100644
--- a/pkg/compiler/lib/src/elements/modelx.dart
+++ b/pkg/compiler/lib/src/elements/modelx.dart
@@ -312,6 +312,9 @@
bool get isRedirectingGenerative => false;
@override
+ bool isRedirectingGenerativeInternal;
+
+ @override
void set isRedirectingGenerative(_) {
throw new UnsupportedError("isRedirectingGenerative");
}
@@ -2222,7 +2225,7 @@
abstract class ConstructorElementX extends FunctionElementX
with ConstantConstructorMixin, ConstructorElementCommon
implements ConstructorElement {
- bool isRedirectingGenerative = false;
+ bool isRedirectingGenerativeInternal = false;
ConstructorElementX(
String name, ElementKind kind, Modifiers modifiers, Element enclosing)
@@ -2233,6 +2236,11 @@
ConstructorElementX get patch => super.patch;
+ bool get isRedirectingGenerative {
+ if (isPatched) return patch.isRedirectingGenerative;
+ return isRedirectingGenerativeInternal;
+ }
+
bool get isRedirectingFactory => immediateRedirectionTarget != null;
// TODO(johnniwinther): This should also return true for cyclic redirecting
diff --git a/pkg/compiler/lib/src/enqueue.dart b/pkg/compiler/lib/src/enqueue.dart
index 12c5a42..b254e0d 100644
--- a/pkg/compiler/lib/src/enqueue.dart
+++ b/pkg/compiler/lib/src/enqueue.dart
@@ -157,7 +157,6 @@
impactVisitor = new _EnqueuerImpactVisitor(this);
}
- // TODO(johnniwinther): Move this to [ResolutionEnqueuer].
Resolution get resolution => compiler.resolution;
ResolutionWorldBuilder get universe => _universe;
diff --git a/pkg/compiler/lib/src/kernel/kernel.dart b/pkg/compiler/lib/src/kernel/kernel.dart
index b4ff25a..53ca782 100644
--- a/pkg/compiler/lib/src/kernel/kernel.dart
+++ b/pkg/compiler/lib/src/kernel/kernel.dart
@@ -194,6 +194,10 @@
if (cls.supertype != null) {
classNode.supertype = interfaceTypeToIr(cls.supertype);
}
+ if (cls.isMixinApplication) {
+ MixinApplicationElement mixinApplication = cls;
+ classNode.mixedInType = interfaceTypeToIr(mixinApplication.mixinType);
+ }
classNode.parent = libraryToIr(cls.library);
if (cls.isUnnamedMixinApplication) {
classNode.enclosingLibrary.addClass(classNode);
@@ -218,6 +222,9 @@
in typesToIr(cls.interfaces.reverse().toList())) {
classNode.implementedTypes.add(interface);
}
+ addWork(cls, () {
+ addDefaultInstanceFieldInitializers(classNode);
+ });
});
addWork(cls.declaration, () {
for (MetadataAnnotation metadata in cls.declaration.metadata) {
@@ -229,6 +236,37 @@
});
}
+ /// Adds initializers to instance fields that are have no initializer and are
+ /// not initialized by all constructors in the class.
+ ///
+ /// This is more or less copied directly from `ast_from_analyzer.dart` in
+ /// dartk.
+ void addDefaultInstanceFieldInitializers(ir.Class node) {
+ List<ir.Field> uninitializedFields = new List<ir.Field>();
+ for (ir.Field field in node.fields) {
+ if (field.initializer != null || field.isStatic) continue;
+ uninitializedFields.add(field);
+ }
+ if (uninitializedFields.isEmpty) return;
+ constructorLoop:
+ for (ir.Constructor constructor in node.constructors) {
+ Set<ir.Field> remainingFields = uninitializedFields.toSet();
+ for (ir.Initializer initializer in constructor.initializers) {
+ if (initializer is ir.FieldInitializer) {
+ remainingFields.remove(initializer.field);
+ } else if (initializer is ir.RedirectingInitializer) {
+ // The target constructor will be checked in another iteration.
+ continue constructorLoop;
+ }
+ }
+ for (ir.Field field in remainingFields) {
+ if (field.initializer == null) {
+ field.initializer = new ir.NullLiteral()..parent = field;
+ }
+ }
+ }
+ }
+
bool hasHierarchyProblem(ClassElement cls) => cls.hasIncompleteHierarchy;
ir.InterfaceType interfaceTypeToIr(InterfaceType type) {
@@ -459,11 +497,15 @@
isConst: field.isConst);
addWork(field, () {
setParent(fieldNode, field);
- if (!field.isMalformed && field.initializer != null) {
- KernelVisitor visitor =
- new KernelVisitor(field, field.treeElements, this);
- fieldNode.initializer = visitor.buildInitializer()
- ..parent = fieldNode;
+ if (!field.isMalformed) {
+ if (field.initializer != null) {
+ KernelVisitor visitor =
+ new KernelVisitor(field, field.treeElements, this);
+ fieldNode.initializer = visitor.buildInitializer()
+ ..parent = fieldNode;
+ } else if (!field.isInstanceMember) {
+ fieldNode.initializer = new ir.NullLiteral()..parent = fieldNode;
+ }
}
});
addWork(field.declaration, () {
diff --git a/pkg/compiler/lib/src/kernel/kernel_debug.dart b/pkg/compiler/lib/src/kernel/kernel_debug.dart
index f86a6a2..d723354 100644
--- a/pkg/compiler/lib/src/kernel/kernel_debug.dart
+++ b/pkg/compiler/lib/src/kernel/kernel_debug.dart
@@ -43,6 +43,11 @@
}
@override
+ void visitStaticGet(StaticGet node) {
+ openAndCloseNode(node, '${node.runtimeType}', {'target': '${node.target}'});
+ }
+
+ @override
void visitVariableDeclaration(VariableDeclaration node) {
openNode(node, '${node.runtimeType}', {
'name': '${node.name ?? '--unnamed--'}',
diff --git a/pkg/compiler/lib/src/native/behavior.dart b/pkg/compiler/lib/src/native/behavior.dart
index 8609630..e34145a 100644
--- a/pkg/compiler/lib/src/native/behavior.dart
+++ b/pkg/compiler/lib/src/native/behavior.dart
@@ -31,6 +31,8 @@
int get hashCode => name.hashCode;
+ String toString() => name;
+
static SpecialType fromName(String name) {
if (name == '=Object') {
return JsObject;
diff --git a/pkg/compiler/lib/src/ordered_typeset.dart b/pkg/compiler/lib/src/ordered_typeset.dart
index e3cffb5..4e37362 100644
--- a/pkg/compiler/lib/src/ordered_typeset.dart
+++ b/pkg/compiler/lib/src/ordered_typeset.dart
@@ -94,7 +94,9 @@
Link<DartType> pointer = _levels[level];
Link<DartType> end =
level > 0 ? _levels[level - 1] : const Link<DartType>();
- while (!identical(pointer, end)) {
+ // TODO(het): checking `isNotEmpty` should be unnecessary, remove when
+ // constants are properly canonicalized
+ while (pointer.isNotEmpty && !identical(pointer, end)) {
f(pointer.head);
pointer = pointer.tail;
}
@@ -107,7 +109,9 @@
Link<DartType> pointer = _levels[level];
Link<DartType> end =
level > 0 ? _levels[level - 1] : const Link<DartType>();
- while (!identical(pointer, end)) {
+ // TODO(het): checking `isNotEmpty` should be unnecessary, remove when
+ // constants are properly canonicalized
+ while (pointer.isNotEmpty && !identical(pointer, end)) {
if (cls == pointer.head.element) {
return pointer.head;
}
diff --git a/pkg/compiler/lib/src/resolution/constructors.dart b/pkg/compiler/lib/src/resolution/constructors.dart
index 9707724..4a37428 100644
--- a/pkg/compiler/lib/src/resolution/constructors.dart
+++ b/pkg/compiler/lib/src/resolution/constructors.dart
@@ -411,7 +411,7 @@
reporter.reportErrorMessage(
call, MessageKind.REDIRECTING_CONSTRUCTOR_HAS_INITIALIZER);
} else {
- constructor.isRedirectingGenerative = true;
+ constructor.isRedirectingGenerativeInternal = true;
}
// Check that there are no field initializing parameters.
FunctionSignature signature = constructor.functionSignature;
diff --git a/pkg/compiler/lib/src/resolution/members.dart b/pkg/compiler/lib/src/resolution/members.dart
index 00b3725..f93553d 100644
--- a/pkg/compiler/lib/src/resolution/members.dart
+++ b/pkg/compiler/lib/src/resolution/members.dart
@@ -85,6 +85,7 @@
/// in static contexts, factory methods, and field initializers).
bool inInstanceContext;
bool inCheckContext;
+ bool inCatchParameters = false;
bool inCatchBlock;
ConstantState constantState;
@@ -4703,6 +4704,7 @@
nodeList, MessageKind.OPTIONAL_PARAMETER_IN_CATCH);
} else {
VariableDefinitions declaration = link.head;
+
for (Node modifier in declaration.modifiers.nodes) {
reporter.reportErrorMessage(
modifier, MessageKind.PARAMETER_WITH_MODIFIER_IN_CATCH);
@@ -4717,15 +4719,17 @@
}
Scope blockScope = new BlockScope(scope);
- TypeResult exceptionTypeResult = visitIn(node.type, blockScope);
+ inCatchParameters = true;
visitIn(node.formals, blockScope);
+ inCatchParameters = false;
var oldInCatchBlock = inCatchBlock;
inCatchBlock = true;
visitIn(node.block, blockScope);
inCatchBlock = oldInCatchBlock;
- if (exceptionTypeResult != null) {
- DartType exceptionType = exceptionTypeResult.type;
+ if (node.type != null) {
+ DartType exceptionType =
+ resolveTypeAnnotation(node.type, registerCheckedModeCheck: false);
if (exceptionDefinition != null) {
Node exceptionVariable = exceptionDefinition.definitions.nodes.head;
VariableElementX exceptionElement =
diff --git a/pkg/compiler/lib/src/resolution/resolution.dart b/pkg/compiler/lib/src/resolution/resolution.dart
index 09ef8f9..ebea1af 100644
--- a/pkg/compiler/lib/src/resolution/resolution.dart
+++ b/pkg/compiler/lib/src/resolution/resolution.dart
@@ -425,7 +425,8 @@
}
});
if (initializer != null) {
- if (!element.modifiers.isConst) {
+ if (!element.modifiers.isConst &&
+ initializer.asLiteralNull() == null) {
// TODO(johnniwinther): Determine the const-ness eagerly to avoid
// unnecessary registrations.
registry.registerFeature(Feature.LAZY_FIELD);
diff --git a/pkg/compiler/lib/src/resolution/variables.dart b/pkg/compiler/lib/src/resolution/variables.dart
index fa7dd75..d6490e0 100644
--- a/pkg/compiler/lib/src/resolution/variables.dart
+++ b/pkg/compiler/lib/src/resolution/variables.dart
@@ -42,8 +42,10 @@
}
Identifier visitIdentifier(Identifier node) {
- // The variable is initialized to null.
- registry.registerFeature(Feature.LOCAL_WITHOUT_INITIALIZER);
+ if (!resolver.inCatchParameters) {
+ // The variable is initialized to null.
+ registry.registerFeature(Feature.LOCAL_WITHOUT_INITIALIZER);
+ }
if (definitions.modifiers.isConst) {
if (resolver.inLoopVariable) {
reporter.reportErrorMessage(node, MessageKind.CONST_LOOP_VARIABLE);
diff --git a/pkg/compiler/lib/src/ssa/kernel_ast_adapter.dart b/pkg/compiler/lib/src/ssa/kernel_ast_adapter.dart
index be4a558..ae86379 100644
--- a/pkg/compiler/lib/src/ssa/kernel_ast_adapter.dart
+++ b/pkg/compiler/lib/src/ssa/kernel_ast_adapter.dart
@@ -15,7 +15,7 @@
import '../js_backend/js_backend.dart';
import '../kernel/kernel.dart';
import '../kernel/kernel_debug.dart';
-import '../native/native.dart' show NativeBehavior;
+import '../native/native.dart' show NativeBehavior, TypeLookup;
import '../resolution/tree_elements.dart';
import '../tree/tree.dart' as ast;
import '../types/masks.dart';
@@ -358,26 +358,32 @@
// TODO(johnniwinther): Use this in [NativeBehavior] instead of calling the
// `ForeignResolver`.
// TODO(johnniwinther): Cache the result to avoid redundant lookups?
- DartType _typeLookup(String typeName) {
- DartType findIn(Uri uri) {
- LibraryElement library = _compiler.libraryLoader.lookupLibrary(uri);
- if (library != null) {
- Element element = library.find(typeName);
- if (element != null && element.isClass) {
- ClassElement cls = element;
- return cls.rawType;
+ TypeLookup _typeLookup({bool resolveAsRaw: true}) {
+ return (String typeName) {
+ DartType findIn(Uri uri) {
+ LibraryElement library = _compiler.libraryLoader.lookupLibrary(uri);
+ if (library != null) {
+ Element element = library.find(typeName);
+ if (element != null && element.isClass) {
+ ClassElement cls = element;
+ // TODO(johnniwinther): Align semantics.
+ return resolveAsRaw ? cls.rawType : cls.thisType;
+ }
}
+ return null;
}
- return null;
- }
- DartType type = findIn(Uris.dart_core);
- type ??= findIn(BackendHelpers.DART_JS_HELPER);
- type ??= findIn(BackendHelpers.DART_INTERCEPTORS);
- type ??= findIn(BackendHelpers.DART_ISOLATE_HELPER);
- type ??= findIn(Uris.dart_collection);
- type ??= findIn(Uris.dart_html);
- return type;
+ DartType type = findIn(Uris.dart_core);
+ type ??= findIn(BackendHelpers.DART_JS_HELPER);
+ type ??= findIn(BackendHelpers.DART_INTERCEPTORS);
+ type ??= findIn(BackendHelpers.DART_ISOLATE_HELPER);
+ type ??= findIn(Uris.dart_collection);
+ type ??= findIn(Uris.dart_html);
+ type ??= findIn(Uris.dart_svg);
+ type ??= findIn(Uris.dart_web_audio);
+ type ??= findIn(Uris.dart_web_gl);
+ return type;
+ };
}
String _getStringArgument(ir.StaticInvocation node, int index) {
@@ -407,8 +413,13 @@
return new NativeBehavior();
}
- return NativeBehavior.ofJsCall(specString, codeString, _typeLookup,
- CURRENT_ELEMENT_SPANNABLE, reporter, _compiler.coreTypes);
+ return NativeBehavior.ofJsCall(
+ specString,
+ codeString,
+ _typeLookup(resolveAsRaw: true),
+ CURRENT_ELEMENT_SPANNABLE,
+ reporter,
+ _compiler.coreTypes);
}
/// Computes the [NativeBehavior] for a call to the [JS_BUILTIN] function.
@@ -430,8 +441,12 @@
CURRENT_ELEMENT_SPANNABLE, "Unexpected first argument.");
return new NativeBehavior();
}
- return NativeBehavior.ofJsBuiltinCall(specString, _typeLookup,
- CURRENT_ELEMENT_SPANNABLE, reporter, _compiler.coreTypes);
+ return NativeBehavior.ofJsBuiltinCall(
+ specString,
+ _typeLookup(resolveAsRaw: true),
+ CURRENT_ELEMENT_SPANNABLE,
+ reporter,
+ _compiler.coreTypes);
}
/// Computes the [NativeBehavior] for a call to the [JS_EMBEDDED_GLOBAL]
@@ -461,8 +476,12 @@
CURRENT_ELEMENT_SPANNABLE, "Unexpected first argument.");
return new NativeBehavior();
}
- return NativeBehavior.ofJsEmbeddedGlobalCall(specString, _typeLookup,
- CURRENT_ELEMENT_SPANNABLE, reporter, _compiler.coreTypes);
+ return NativeBehavior.ofJsEmbeddedGlobalCall(
+ specString,
+ _typeLookup(resolveAsRaw: true),
+ CURRENT_ELEMENT_SPANNABLE,
+ reporter,
+ _compiler.coreTypes);
}
/// Returns `true` is [node] has a `@Native(...)` annotation.
@@ -485,8 +504,8 @@
NativeBehavior getNativeBehaviorForFieldLoad(ir.Field field) {
DartType type = getDartType(field.type);
List<ConstantExpression> metadata = getMetadata(field.annotations);
- return NativeBehavior.ofFieldLoad(
- CURRENT_ELEMENT_SPANNABLE, type, metadata, _typeLookup, _compiler,
+ return NativeBehavior.ofFieldLoad(CURRENT_ELEMENT_SPANNABLE, type, metadata,
+ _typeLookup(resolveAsRaw: false), _compiler,
isJsInterop: false);
}
@@ -502,8 +521,8 @@
NativeBehavior getNativeBehaviorForMethod(ir.Procedure procedure) {
DartType type = getFunctionType(procedure.function);
List<ConstantExpression> metadata = getMetadata(procedure.annotations);
- return NativeBehavior.ofMethod(
- CURRENT_ELEMENT_SPANNABLE, type, metadata, _typeLookup, _compiler,
+ return NativeBehavior.ofMethod(CURRENT_ELEMENT_SPANNABLE, type, metadata,
+ _typeLookup(resolveAsRaw: false), _compiler,
isJsInterop: false);
}
}
@@ -639,6 +658,17 @@
}
@override
+ ConstantExpression visitStaticGet(ir.StaticGet node) {
+ Element element = astAdapter.getMember(node.target);
+ if (element.isField) {
+ return new VariableConstantExpression(element);
+ }
+ astAdapter.reporter.internalError(
+ CURRENT_ELEMENT_SPANNABLE, "Unexpected constant target: $element.");
+ return null;
+ }
+
+ @override
ConstantExpression visitStringLiteral(ir.StringLiteral node) {
return new StringConstantExpression(node.value);
}
diff --git a/pkg/compiler/lib/src/ssa/kernel_impact.dart b/pkg/compiler/lib/src/ssa/kernel_impact.dart
index c035c2d..155c10e 100644
--- a/pkg/compiler/lib/src/ssa/kernel_impact.dart
+++ b/pkg/compiler/lib/src/ssa/kernel_impact.dart
@@ -107,11 +107,11 @@
checkType(field.type);
if (field.initializer != null) {
visitNode(field.initializer);
- if (!field.isInstanceMember && !field.isConst) {
+ if (!field.isInstanceMember &&
+ !field.isConst &&
+ field.initializer is! ir.NullLiteral) {
impactBuilder.registerFeature(Feature.LAZY_FIELD);
}
- } else {
- impactBuilder.registerFeature(Feature.FIELD_WITHOUT_INITIALIZER);
}
if (field.isInstanceMember && astAdapter.isNative(field.enclosingClass)) {
impactBuilder
@@ -532,7 +532,6 @@
@override
void visitCatch(ir.Catch node) {
impactBuilder.registerFeature(Feature.CATCH_STATEMENT);
- visitNode(node.exception);
if (node.stackTrace != null) {
impactBuilder.registerFeature(Feature.STACK_TRACE_IN_CATCH);
}
diff --git a/pkg/compiler/tool/dart2js_profile_many.dart b/pkg/compiler/tool/dart2js_profile_many.dart
index ba344e0..fed5e21 100644
--- a/pkg/compiler/tool/dart2js_profile_many.dart
+++ b/pkg/compiler/tool/dart2js_profile_many.dart
@@ -6,7 +6,7 @@
import 'dart:async';
-import 'package:compiler/src/dart2js.dart' as cmdline
+import 'package:compiler/src/dart2js.dart' as cmdline;
const String USAGE = """
Usage: dart2js_profile_many.dart [OPTIONS] [FILES]
diff --git a/pkg/dev_compiler/lib/js/amd/dart_sdk.js b/pkg/dev_compiler/lib/js/amd/dart_sdk.js
index b809f1f..2049dda 100644
--- a/pkg/dev_compiler/lib/js/amd/dart_sdk.js
+++ b/pkg/dev_compiler/lib/js/amd/dart_sdk.js
@@ -1938,6 +1938,9 @@
}
return name;
};
+ dart.loadLibrary = function() {
+ return async.Future.value();
+ };
dart.defineProperty = function(obj, name, desc) {
return Object.defineProperty(obj, name, desc);
};
@@ -28817,9 +28820,7 @@
let const$28;
let const$29;
convert.Codec$ = dart.generic((S, T) => {
- let _FusedCodecOfS$T$dynamic = () => (_FusedCodecOfS$T$dynamic = dart.constFn(convert._FusedCodec$(S, T, dart.dynamic)))();
let _InvertedCodecOfT$S = () => (_InvertedCodecOfT$S = dart.constFn(convert._InvertedCodec$(T, S)))();
- let CodecOfT$dynamic = () => (CodecOfT$dynamic = dart.constFn(convert.Codec$(T, dart.dynamic)))();
class Codec extends core.Object {
new() {
}
@@ -28831,9 +28832,11 @@
T._check(encoded);
return this.decoder.convert(encoded);
}
- fuse(other) {
- CodecOfT$dynamic()._check(other);
- return new (_FusedCodecOfS$T$dynamic())(this, other);
+ fuse(R) {
+ return other => {
+ convert.Codec$(T, R)._check(other);
+ return new (convert._FusedCodec$(S, T, R))(this, other);
+ };
}
get inverted() {
return new (_InvertedCodecOfT$S())(this);
@@ -28846,7 +28849,7 @@
methods: () => ({
encode: dart.definiteFunctionType(T, [S]),
decode: dart.definiteFunctionType(S, [T]),
- fuse: dart.definiteFunctionType(convert.Codec$(S, dart.dynamic), [CodecOfT$dynamic()])
+ fuse: dart.definiteFunctionType(R => [convert.Codec$(S, R), [convert.Codec$(T, R)]])
})
});
return Codec;
@@ -35940,7 +35943,7 @@
if (dart.test(base64)) {
buffer.write(';base64,');
indices[dartx.add](dart.notNull(buffer.length) - 1);
- buffer.write(encoding.fuse(convert.BASE64).encode(content));
+ buffer.write(encoding.fuse(core.String)(convert.BASE64).encode(content));
} else {
buffer.write(',');
core.UriData._uriEncodeBytes(core.UriData._uricTable, encoding.encode(content), buffer);
diff --git a/pkg/dev_compiler/lib/js/common/dart_sdk.js b/pkg/dev_compiler/lib/js/common/dart_sdk.js
index 6615391..6f93ee1 100644
--- a/pkg/dev_compiler/lib/js/common/dart_sdk.js
+++ b/pkg/dev_compiler/lib/js/common/dart_sdk.js
@@ -1938,6 +1938,9 @@
}
return name;
};
+ dart.loadLibrary = function() {
+ return async.Future.value();
+ };
dart.defineProperty = function(obj, name, desc) {
return Object.defineProperty(obj, name, desc);
};
@@ -28817,9 +28820,7 @@
let const$28;
let const$29;
convert.Codec$ = dart.generic((S, T) => {
- let _FusedCodecOfS$T$dynamic = () => (_FusedCodecOfS$T$dynamic = dart.constFn(convert._FusedCodec$(S, T, dart.dynamic)))();
let _InvertedCodecOfT$S = () => (_InvertedCodecOfT$S = dart.constFn(convert._InvertedCodec$(T, S)))();
- let CodecOfT$dynamic = () => (CodecOfT$dynamic = dart.constFn(convert.Codec$(T, dart.dynamic)))();
class Codec extends core.Object {
new() {
}
@@ -28831,9 +28832,11 @@
T._check(encoded);
return this.decoder.convert(encoded);
}
- fuse(other) {
- CodecOfT$dynamic()._check(other);
- return new (_FusedCodecOfS$T$dynamic())(this, other);
+ fuse(R) {
+ return other => {
+ convert.Codec$(T, R)._check(other);
+ return new (convert._FusedCodec$(S, T, R))(this, other);
+ };
}
get inverted() {
return new (_InvertedCodecOfT$S())(this);
@@ -28846,7 +28849,7 @@
methods: () => ({
encode: dart.definiteFunctionType(T, [S]),
decode: dart.definiteFunctionType(S, [T]),
- fuse: dart.definiteFunctionType(convert.Codec$(S, dart.dynamic), [CodecOfT$dynamic()])
+ fuse: dart.definiteFunctionType(R => [convert.Codec$(S, R), [convert.Codec$(T, R)]])
})
});
return Codec;
@@ -35940,7 +35943,7 @@
if (dart.test(base64)) {
buffer.write(';base64,');
indices[dartx.add](dart.notNull(buffer.length) - 1);
- buffer.write(encoding.fuse(convert.BASE64).encode(content));
+ buffer.write(encoding.fuse(core.String)(convert.BASE64).encode(content));
} else {
buffer.write(',');
core.UriData._uriEncodeBytes(core.UriData._uricTable, encoding.encode(content), buffer);
diff --git a/pkg/dev_compiler/lib/js/es6/dart_sdk.js b/pkg/dev_compiler/lib/js/es6/dart_sdk.js
index ba30bab..8bb83db 100644
--- a/pkg/dev_compiler/lib/js/es6/dart_sdk.js
+++ b/pkg/dev_compiler/lib/js/es6/dart_sdk.js
@@ -1936,6 +1936,9 @@
}
return name;
};
+dart.loadLibrary = function() {
+ return async.Future.value();
+};
dart.defineProperty = function(obj, name, desc) {
return Object.defineProperty(obj, name, desc);
};
@@ -28815,9 +28818,7 @@
let const;
let const;
convert.Codec$ = dart.generic((S, T) => {
- let _FusedCodecOfS$T$dynamic = () => (_FusedCodecOfS$T$dynamic = dart.constFn(convert._FusedCodec$(S, T, dart.dynamic)))();
let _InvertedCodecOfT$S = () => (_InvertedCodecOfT$S = dart.constFn(convert._InvertedCodec$(T, S)))();
- let CodecOfT$dynamic = () => (CodecOfT$dynamic = dart.constFn(convert.Codec$(T, dart.dynamic)))();
class Codec extends core.Object {
new() {
}
@@ -28829,9 +28830,11 @@
T._check(encoded);
return this.decoder.convert(encoded);
}
- fuse(other) {
- CodecOfT$dynamic()._check(other);
- return new (_FusedCodecOfS$T$dynamic())(this, other);
+ fuse(R) {
+ return other => {
+ convert.Codec$(T, R)._check(other);
+ return new (convert._FusedCodec$(S, T, R))(this, other);
+ };
}
get inverted() {
return new (_InvertedCodecOfT$S())(this);
@@ -28844,7 +28847,7 @@
methods: () => ({
encode: dart.definiteFunctionType(T, [S]),
decode: dart.definiteFunctionType(S, [T]),
- fuse: dart.definiteFunctionType(convert.Codec$(S, dart.dynamic), [CodecOfT$dynamic()])
+ fuse: dart.definiteFunctionType(R => [convert.Codec$(S, R), [convert.Codec$(T, R)]])
})
});
return Codec;
@@ -35938,7 +35941,7 @@
if (dart.test(base64)) {
buffer.write(';base64,');
indices[dartx.add](dart.notNull(buffer.length) - 1);
- buffer.write(encoding.fuse(convert.BASE64).encode(content));
+ buffer.write(encoding.fuse(core.String)(convert.BASE64).encode(content));
} else {
buffer.write(',');
core.UriData._uriEncodeBytes(core.UriData._uricTable, encoding.encode(content), buffer);
diff --git a/pkg/dev_compiler/lib/js/legacy/dart_sdk.js b/pkg/dev_compiler/lib/js/legacy/dart_sdk.js
index c230e85..c1fe1c2 100644
--- a/pkg/dev_compiler/lib/js/legacy/dart_sdk.js
+++ b/pkg/dev_compiler/lib/js/legacy/dart_sdk.js
@@ -1939,6 +1939,9 @@
}
return name;
};
+ dart.loadLibrary = function() {
+ return async.Future.value();
+ };
dart.defineProperty = function(obj, name, desc) {
return Object.defineProperty(obj, name, desc);
};
@@ -28818,9 +28821,7 @@
let const$28;
let const$29;
convert.Codec$ = dart.generic((S, T) => {
- let _FusedCodecOfS$T$dynamic = () => (_FusedCodecOfS$T$dynamic = dart.constFn(convert._FusedCodec$(S, T, dart.dynamic)))();
let _InvertedCodecOfT$S = () => (_InvertedCodecOfT$S = dart.constFn(convert._InvertedCodec$(T, S)))();
- let CodecOfT$dynamic = () => (CodecOfT$dynamic = dart.constFn(convert.Codec$(T, dart.dynamic)))();
class Codec extends core.Object {
new() {
}
@@ -28832,9 +28833,11 @@
T._check(encoded);
return this.decoder.convert(encoded);
}
- fuse(other) {
- CodecOfT$dynamic()._check(other);
- return new (_FusedCodecOfS$T$dynamic())(this, other);
+ fuse(R) {
+ return other => {
+ convert.Codec$(T, R)._check(other);
+ return new (convert._FusedCodec$(S, T, R))(this, other);
+ };
}
get inverted() {
return new (_InvertedCodecOfT$S())(this);
@@ -28847,7 +28850,7 @@
methods: () => ({
encode: dart.definiteFunctionType(T, [S]),
decode: dart.definiteFunctionType(S, [T]),
- fuse: dart.definiteFunctionType(convert.Codec$(S, dart.dynamic), [CodecOfT$dynamic()])
+ fuse: dart.definiteFunctionType(R => [convert.Codec$(S, R), [convert.Codec$(T, R)]])
})
});
return Codec;
@@ -35941,7 +35944,7 @@
if (dart.test(base64)) {
buffer.write(';base64,');
indices[dartx.add](dart.notNull(buffer.length) - 1);
- buffer.write(encoding.fuse(convert.BASE64).encode(content));
+ buffer.write(encoding.fuse(core.String)(convert.BASE64).encode(content));
} else {
buffer.write(',');
core.UriData._uriEncodeBytes(core.UriData._uricTable, encoding.encode(content), buffer);
diff --git a/pkg/dev_compiler/lib/sdk/ddc_sdk.sum b/pkg/dev_compiler/lib/sdk/ddc_sdk.sum
index 5b9947b..9e1cea1 100644
--- a/pkg/dev_compiler/lib/sdk/ddc_sdk.sum
+++ b/pkg/dev_compiler/lib/sdk/ddc_sdk.sum
Binary files differ
diff --git a/pkg/dev_compiler/lib/src/compiler/code_generator.dart b/pkg/dev_compiler/lib/src/compiler/code_generator.dart
index d2f3f8f..19e46d4 100644
--- a/pkg/dev_compiler/lib/src/compiler/code_generator.dart
+++ b/pkg/dev_compiler/lib/src/compiler/code_generator.dart
@@ -3274,6 +3274,11 @@
@override
visitMethodInvocation(MethodInvocation node) {
+ if (_isDeferredLoadLibrary(node.target, node.methodName)) {
+ // We are calling loadLibrary() on a deferred library prefix.
+ return _callHelper('loadLibrary()');
+ }
+
if (node.operator?.lexeme == '?.') {
return _emitNullSafe(node);
}
@@ -4541,6 +4546,11 @@
@override
visitPrefixedIdentifier(PrefixedIdentifier node) {
+ if (_isDeferredLoadLibrary(node.prefix, node.identifier)) {
+ // We are tearing off "loadLibrary" on a library prefix.
+ return _callHelper('loadLibrary');
+ }
+
if (isLibraryPrefix(node.prefix)) {
return _visit(node.identifier);
} else {
@@ -5578,3 +5588,23 @@
bool _isDartRuntime(LibraryElement l) =>
l.isInSdk && l.source.uri.toString() == 'dart:_runtime';
+
+/// Returns `true` if [target] is a prefix for a deferred library and [name]
+/// is "loadLibrary".
+///
+/// If so, the expression should be compiled to call the runtime's
+/// "loadLibrary" helper function.
+bool _isDeferredLoadLibrary(Expression target, SimpleIdentifier name) {
+ if (name.name != "loadLibrary") return false;
+
+ if (target is! SimpleIdentifier) return false;
+ var targetIdentifier = target as SimpleIdentifier;
+
+ if (targetIdentifier.staticElement is! PrefixElement) return false;
+ var prefix = targetIdentifier.staticElement as PrefixElement;
+
+ // The library the prefix is referring to must come from a deferred import.
+ var containingLibrary = (target.root as CompilationUnit).element.library;
+ var imports = containingLibrary.getImportsWithPrefix(prefix);
+ return imports.length == 1 && imports[0].isDeferred;
+}
diff --git a/pkg/dev_compiler/lib/src/compiler/command.dart b/pkg/dev_compiler/lib/src/compiler/command.dart
index d97ae11..87b2a57 100644
--- a/pkg/dev_compiler/lib/src/compiler/command.dart
+++ b/pkg/dev_compiler/lib/src/compiler/command.dart
@@ -91,13 +91,13 @@
}
void _compile(ArgResults argResults, void printFn(Object obj)) {
- var compiler =
- new ModuleCompiler(new AnalyzerOptions.fromArguments(argResults));
- var compilerOpts = new CompilerOptions.fromArguments(argResults);
if (argResults['help']) {
printFn(_usageMessage);
return;
}
+ var compiler =
+ new ModuleCompiler(new AnalyzerOptions.fromArguments(argResults));
+ var compilerOpts = new CompilerOptions.fromArguments(argResults);
var outPaths = argResults['out'] as List<String>;
var moduleFormats = parseModuleFormatOption(argResults);
bool singleOutFile = argResults['single-out-file'];
diff --git a/pkg/dev_compiler/test/browser/language_tests.js b/pkg/dev_compiler/test/browser/language_tests.js
index 378ac92..948d48a 100644
--- a/pkg/dev_compiler/test/browser/language_tests.js
+++ b/pkg/dev_compiler/test/browser/language_tests.js
@@ -124,22 +124,15 @@
'cyclic_type_test_03_multi': skip_fail,
'cyclic_type_test_04_multi': skip_fail,
'cyclic_type_variable_test_none_multi': skip_fail,
+
+ // Deferred libraries are not actually deferred. These tests all test
+ // that synchronous access to the library fails.
'deferred_call_empty_before_load_test': skip_fail,
- 'deferred_closurize_load_library_test': skip_fail,
- 'deferred_constant_list_test': skip_fail,
- 'deferred_function_type_test': skip_fail,
- 'deferred_inlined_test': skip_fail,
- 'deferred_load_inval_code_test': skip_fail,
- 'deferred_mixin_test': skip_fail,
- 'deferred_no_such_method_test': skip_fail, // deferred libs not implemented
'deferred_not_loaded_check_test': skip_fail,
- 'deferred_only_constant_test': skip_fail,
- 'deferred_optimized_test': skip_fail,
'deferred_redirecting_factory_test': skip_fail,
- 'deferred_regression_22995_test': skip_fail,
- 'deferred_shadow_load_library_test': skip_fail,
- 'deferred_shared_and_unshared_classes_test': skip_fail,
'deferred_static_seperate_test': skip_fail,
+
+ 'deferred_regression_22995_test': skip_fail, // Strong mode "is" rejects some type tests.
'double_int_to_string_test': skip_fail,
'double_to_string_test': skip_fail,
'dynamic_test': skip_fail,
diff --git a/pkg/dev_compiler/tool/input_sdk/lib/convert/codec.dart b/pkg/dev_compiler/tool/input_sdk/lib/convert/codec.dart
index 3fc2d31..7f42c86 100644
--- a/pkg/dev_compiler/tool/input_sdk/lib/convert/codec.dart
+++ b/pkg/dev_compiler/tool/input_sdk/lib/convert/codec.dart
@@ -62,8 +62,8 @@
*/
// TODO(floitsch): use better example with line-splitter once that one is
// in this library.
- Codec<S, dynamic> fuse(Codec<T, dynamic> other) {
- return new _FusedCodec<S, T, dynamic>(this, other);
+ Codec<S, dynamic/*=R*/> fuse/*<R>*/(Codec<T, dynamic/*=R*/> other) {
+ return new _FusedCodec<S, T, dynamic/*=R*/>(this, other);
}
/**
diff --git a/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart b/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart
index 5553144..c4a1d776 100644
--- a/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart
+++ b/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart
@@ -847,3 +847,9 @@
}
return name;
}
+
+/// Emulates the implicit "loadLibrary" function provided by a deferred library.
+///
+/// Libraries are not actually deferred in DDC, so this just returns a future
+/// that completes immediately.
+Future loadLibrary() => new Future.value();
diff --git a/pkg/dev_compiler/tool/sdk_expected_errors.txt b/pkg/dev_compiler/tool/sdk_expected_errors.txt
index 81c8204..8e0b1c4 100644
--- a/pkg/dev_compiler/tool/sdk_expected_errors.txt
+++ b/pkg/dev_compiler/tool/sdk_expected_errors.txt
@@ -5,86 +5,14 @@
[error] Invalid override. The type of 'ChunkedConverter.startChunkedConversion' ('(dynamic) → dynamic') isn't a subtype of 'Converter<S, T>.startChunkedConversion' ('(Sink<T>) → Sink<S>'). (dart:convert/chunked_conversion.dart, line 15, col 3)
[error] Invalid override. The type of '_EventStreamSubscription.asFuture' ('([dynamic]) → Future<dynamic>') isn't a subtype of 'StreamSubscription<T>.asFuture' ('<E>([E]) → Future<E>'). (dart:html, line 40152, col 3)
[error] Invalid override. The type of 'JsArray.[]=' ('(Object, E) → void') isn't a subtype of 'JsObject.[]=' ('(Object, dynamic) → dynamic'). (dart:js, line 363, col 3)
-[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:_debugger, line 39, col 45)
-[warning] Unsound implicit cast from 'dynamic' to 'List<NameValuePair>'. (dart:_debugger, line 750, col 43)
-[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:_isolate_helper, line 839, col 37)
-[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:_isolate_helper, line 886, col 11)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 117, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 159, col 17)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 167, col 17)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 198, col 27)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 239, col 27)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 252, col 27)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 264, col 27)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 277, col 27)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 295, col 16)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 300, col 17)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 443, col 27)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 455, col 27)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 564, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'JSArray<String>'. (dart:_js_helper, line 79, col 37)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_js_helper, line 882, col 16)
-[warning] Unsound implicit cast from 'dynamic' to '() → List<Type>'. (dart:_js_mirrors, line 425, col 40)
-[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:_interceptors/js_string.dart, line 92, col 14)
-[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:_interceptors/js_string.dart, line 95, col 14)
-[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:_js_helper/linked_hash_map.dart, line 119, col 40)
-[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:_js_helper/linked_hash_map.dart, line 148, col 44)
-[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:_js_helper/linked_hash_map.dart, line 183, col 9)
-[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:_js_helper/linked_hash_map.dart, line 299, col 42)
-[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:_js_helper/linked_hash_map.dart, line 308, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'List<LinkedHashMapCell<K, V>>'. (dart:_js_helper/linked_hash_map.dart, line 312, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:_js_helper/linked_hash_map.dart, line 346, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'List<LinkedHashMapCell<K, V>>'. (dart:_js_helper/linked_hash_map.dart, line 351, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:_js_helper/regexp_helper.dart, line 108, col 22)
-[warning] Unsound implicit cast from 'List<dynamic>' to 'List<String>'. (dart:_js_helper/regexp_helper.dart, line 140, col 43)
-[warning] Unsound implicit cast from 'List<dynamic>' to 'List<String>'. (dart:_js_helper/regexp_helper.dart, line 152, col 43)
-[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 105, col 14)
-[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 108, col 14)
-[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 119, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 186, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'K'. (dart:collection, line 200, col 14)
-[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 268, col 17)
-[warning] Unsound implicit cast from 'dynamic' to 'K'. (dart:collection, line 404, col 49)
-[warning] Unsound implicit cast from 'dynamic' to 'K'. (dart:collection, line 411, col 19)
-[warning] Unsound implicit cast from 'Object' to 'K'. (dart:collection, line 411, col 49)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 436, col 9)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 462, col 18)
-[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:collection, line 495, col 42)
-[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 532, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'K'. (dart:collection, line 569, col 14)
-[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 569, col 19)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 614, col 9)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 653, col 18)
-[warning] Unsound implicit cast from 'dynamic' to 'K'. (dart:collection, line 689, col 49)
-[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:collection, line 696, col 42)
-[warning] Unsound implicit cast from 'dynamic' to 'K'. (dart:collection, line 697, col 40)
-[warning] Unsound implicit cast from 'Object' to 'E'. (dart:collection, line 758, col 14)
-[warning] Unsound implicit cast from 'dynamic' to 'List<E>'. (dart:collection, line 951, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1009, col 21)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1009, col 51)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1019, col 47)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1058, col 18)
-[warning] Unsound implicit cast from 'Object' to 'E'. (dart:collection, line 1135, col 14)
-[warning] Unsound implicit cast from 'dynamic' to '_LinkedHashSetCell<E>'. (dart:collection, line 1222, col 38)
-[warning] Unsound implicit cast from 'dynamic' to '_LinkedHashSetCell<E>'. (dart:collection, line 1337, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'List<_LinkedHashSetCell<E>>'. (dart:collection, line 1351, col 12)
-[warning] Unsound implicit cast from 'dynamic' to '_LinkedHashSetCell<E>'. (dart:collection, line 1358, col 40)
-[warning] Unsound implicit cast from 'dynamic' to '_LinkedHashSetCell<E>'. (dart:collection, line 1391, col 40)
-[warning] Unsound implicit cast from 'dynamic' to '_LinkedHashSetCell<E>'. (dart:collection, line 1412, col 40)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1413, col 36)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1423, col 47)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1485, col 18)
-[warning] Unsound implicit cast from 'dynamic' to 'Stream<S>'. (dart:convert/chunked_conversion.dart, line 14, col 45)
-[warning] Unsound implicit cast from 'dynamic' to 'Sink<T>'. (dart:convert/chunked_conversion.dart, line 16, col 36)
-[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:convert, line 311, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'T'. (dart:core/expando.dart, line 55, col 12)
-[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:core/list.dart, line 126, col 16)
+[warning] Unsafe implicit cast from 'List<dynamic>' to 'List<String>'. This usually indicates that type information was lost and resulted in 'dynamic' and/or a place that will have a failure at runtime. (dart:_js_helper/regexp_helper.dart, line 140, col 43)
+[warning] Unsafe implicit cast from 'List<dynamic>' to 'List<String>'. This usually indicates that type information was lost and resulted in 'dynamic' and/or a place that will have a failure at runtime. (dart:_js_helper/regexp_helper.dart, line 152, col 43)
+[warning] Unsafe implicit cast from 'Object' to 'K'. This usually indicates that type information was lost and resulted in 'dynamic' and/or a place that will have a failure at runtime. (dart:collection, line 411, col 49)
+[warning] Unsafe implicit cast from 'Object' to 'E'. This usually indicates that type information was lost and resulted in 'dynamic' and/or a place that will have a failure at runtime. (dart:collection, line 758, col 14)
+[warning] Unsafe implicit cast from 'Object' to 'E'. This usually indicates that type information was lost and resulted in 'dynamic' and/or a place that will have a failure at runtime. (dart:collection, line 1135, col 14)
[warning] The final variable 'origin' must be initialized. (dart:html, line 177, col 3)
[warning] The final variable 'origin' must be initialized. (dart:html, line 813, col 3)
-[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:html, line 1145, col 33)
[warning] The final variables 'form', 'labels' and '3' more must be initialized. (dart:html, line 1691, col 3)
-[warning] Unsound implicit cast from 'dynamic' to 'List<num>'. (dart:html, line 2723, col 14)
-[warning] Unsound implicit cast from 'dynamic' to 'List<num>'. (dart:html, line 2725, col 14)
[warning] The final variable 'options' must be initialized. (dart:html, line 8972, col 3)
[warning] The final variables '_attributes', '_childElementCount' and '16' more must be initialized. (dart:html, line 13009, col 3)
[warning] The final variables 'elements', 'form' and '4' more must be initialized. (dart:html, line 16625, col 3)
@@ -114,14 +42,11 @@
[warning] The final variables 'form', 'labels' and '5' more must be initialized. (dart:html, line 32069, col 3)
[warning] The final variables 'readyState' and 'track' must be initialized. (dart:html, line 33056, col 3)
[warning] The final variables 'decodedFrameCount', 'droppedFrameCount' and '2' more must be initialized. (dart:html, line 33754, col 3)
-[warning] Unsound implicit cast from 'dynamic' to 'Rectangle<num>'. (dart:html, line 37618, col 14)
-[warning] Unsound implicit cast from 'dynamic' to 'Rectangle<num>'. (dart:html, line 37626, col 14)
-[warning] Unsound implicit cast from 'dynamic' to 'Rectangle<num>'. (dart:html, line 37634, col 14)
-[warning] Unsound implicit cast from '(T) → void' to '(Event) → dynamic'. (dart:html, line 40090, col 67)
-[warning] Unsound implicit cast from '(T) → void' to '(Event) → dynamic'. (dart:html, line 40112, col 45)
-[warning] Unsound implicit cast from 'num' to 'T'. (dart:math/rectangle.dart, line 158, col 22)
-[warning] Unsound implicit cast from 'num' to 'T'. (dart:math/rectangle.dart, line 159, col 23)
-[warning] Unsound implicit cast from 'num' to 'T'. (dart:math/rectangle.dart, line 282, col 10)
+[warning] Unsafe implicit cast from '(T) → void' to '(Event) → dynamic'. This usually indicates that type information was lost and resulted in 'dynamic' and/or a place that will have a failure at runtime. (dart:html, line 40090, col 67)
+[warning] Unsafe implicit cast from '(T) → void' to '(Event) → dynamic'. This usually indicates that type information was lost and resulted in 'dynamic' and/or a place that will have a failure at runtime. (dart:html, line 40112, col 45)
+[warning] Unsafe implicit cast from 'num' to 'T'. This usually indicates that type information was lost and resulted in 'dynamic' and/or a place that will have a failure at runtime. (dart:math/rectangle.dart, line 158, col 22)
+[warning] Unsafe implicit cast from 'num' to 'T'. This usually indicates that type information was lost and resulted in 'dynamic' and/or a place that will have a failure at runtime. (dart:math/rectangle.dart, line 159, col 23)
+[warning] Unsafe implicit cast from 'num' to 'T'. This usually indicates that type information was lost and resulted in 'dynamic' and/or a place that will have a failure at runtime. (dart:math/rectangle.dart, line 282, col 10)
[warning] The final variables 'href' and 'target' must be initialized. (dart:svg, line 60, col 3)
[warning] The final variables 'requiredExtensions', 'requiredFeatures' and '2' more must be initialized. (dart:svg, line 489, col 3)
[warning] The final variables 'cx', 'cy' and '1' more must be initialized. (dart:svg, line 562, col 3)
diff --git a/pkg/meta/lib/meta.dart b/pkg/meta/lib/meta.dart
index 9842875..7fa20e1 100644
--- a/pkg/meta/lib/meta.dart
+++ b/pkg/meta/lib/meta.dart
@@ -18,6 +18,14 @@
/// in the language tour.
library meta;
+/// Used to annotate a parameter of an instance method that overrides another
+/// method.
+///
+/// Indicates that this parameter may have a tighter type than the parameter on
+/// its superclass. The actual argument will be checked at runtime to ensure it
+/// is a subtype of the overridden parameter type.
+const _Checked checked = const _Checked();
+
/// Used to annotate an instance or static method `m`. Indicates that `m` must
/// either be abstract or must return a newly allocated object or `null`. In
/// addition, every method that either implements or overrides `m` is implicitly
@@ -30,6 +38,18 @@
/// can return anything other than a newly allocated object or `null`.
const _Factory factory = const _Factory();
+/// Used to annotate a class `C`. Indicates that `C` and all subtypes of `C`
+/// must be immutable.
+///
+/// A class is immutable if all of the instance fields of the class, whether
+/// defined directly or inherited, are `final`.
+///
+/// Tools, such as the analyzer, can provide feedback if
+/// * the annotation is associated with anything other than a class, or
+/// * a class that has this annotation or extends, implements or mixes in a
+/// class that has this annotation is not immutable.
+const Immutable immutable = const Immutable();
+
/// Used to annotate a const constructor `c`. Indicates that any invocation of
/// the constructor must use the keyword `const` unless one or more of the
/// arguments to the constructor is not a compile-time constant.
@@ -97,6 +117,9 @@
/// corresponding to a named parameter that has this annotation.
const Required required = const Required();
+/// Used to annotate a field is allowed to be overridden in Strong Mode.
+const _Virtual virtual = const _Virtual();
+
/// Used to annotate a declaration was made public, so that it is more visible
/// than otherwise necessary, to make code testable.
///
@@ -109,6 +132,17 @@
/// library which is in the `test` folder of the defining package.
const _VisibleForTesting visibleForTesting = const _VisibleForTesting();
+/// Used to annotate a class.
+///
+/// See [immutable] for more details.
+class Immutable {
+ /// A human-readable explanation of the reason why the class is immutable.
+ final String reason;
+
+ /// Initialize a newly created instance to have the given [reason].
+ const Immutable([this.reason]);
+}
+
/// Used to annotate a named parameter `p` in a method or function `f`.
///
/// See [required] for more details.
@@ -128,17 +162,6 @@
const Required([this.reason]);
}
-/// Used to annotate a parameter of an instance method that overrides another
-/// method.
-///
-/// Indicates that this parameter may have a tighter type than the parameter on
-/// its superclass. The actual argument will be checked at runtime to ensure it
-/// is a subtype of the overridden parameter type.
-const _Checked checked = const _Checked();
-
-/// Used to annotate a field is allowed to be overridden in Strong Mode.
-const _Virtual virtual = const _Virtual();
-
class _Checked {
const _Checked();
}
diff --git a/runtime/bin/address_sanitizer.cc b/runtime/bin/address_sanitizer.cc
index 6795da8..db2c65e 100644
--- a/runtime/bin/address_sanitizer.cc
+++ b/runtime/bin/address_sanitizer.cc
@@ -8,17 +8,16 @@
#if defined(__has_feature)
#if __has_feature(address_sanitizer)
-const char *kAsanDefaultOptions =
+const char* kAsanDefaultOptions =
"strict_memcmp=0 symbolize=0 check_printf=1 use_sigaltstack=1 "
"detect_leaks=0 fast_unwind_on_fatal=1 handle_segv=0 ";
-extern "C"
-__attribute__((no_sanitize_address))
+extern "C" __attribute__((no_sanitize_address))
__attribute__((visibility("default")))
// The function isn't referenced from the executable itself. Make sure it isn't
// stripped by the linker.
-__attribute__((used))
-const char *__asan_default_options() {
+__attribute__((used)) const char*
+__asan_default_options() {
return kAsanDefaultOptions;
}
diff --git a/runtime/bin/builtin.cc b/runtime/bin/builtin.cc
index b3215bb..49ebb05 100644
--- a/runtime/bin/builtin.cc
+++ b/runtime/bin/builtin.cc
@@ -14,30 +14,29 @@
namespace bin {
Builtin::builtin_lib_props Builtin::builtin_libraries_[] = {
- /* { url_, source_, patch_url_, patch_source_, has_natives_ } */
- { DartUtils::kBuiltinLibURL, _builtin_source_paths_, NULL, NULL, true },
- { DartUtils::kIOLibURL, io_source_paths_,
- DartUtils::kIOLibPatchURL, io_patch_paths_, true },
+ /* { url_, source_, patch_url_, patch_source_, has_natives_ } */
+ {DartUtils::kBuiltinLibURL, _builtin_source_paths_, NULL, NULL, true},
+ {DartUtils::kIOLibURL, io_source_paths_, DartUtils::kIOLibPatchURL,
+ io_patch_paths_, true},
#if defined(DART_NO_SNAPSHOT)
- // Only include these libraries in the dart_bootstrap case for now.
- { "dart:html", html_source_paths_, NULL, NULL, true },
- { "dart:html_common", html_common_source_paths_, NULL, NULL, true},
- { "dart:js", js_source_paths_, NULL, NULL, true},
- { "dart:js_util", js_util_source_paths_, NULL, NULL, true},
- { "dart:_blink", _blink_source_paths_, NULL, NULL, true },
- { "dart:indexed_db", indexed_db_source_paths_, NULL, NULL, true },
- { "cached_patches.dart", cached_patches_source_paths_, NULL, NULL, true },
- { "dart:web_gl", web_gl_source_paths_, NULL, NULL, true },
- { "metadata.dart", metadata_source_paths_, NULL, NULL, true },
- { "dart:web_sql", web_sql_source_paths_, NULL, NULL, true },
- { "dart:svg", svg_source_paths_, NULL, NULL, true },
- { "dart:web_audio", web_audio_source_paths_, NULL, NULL, true },
+ // Only include these libraries in the dart_bootstrap case for now.
+ {"dart:html", html_source_paths_, NULL, NULL, true},
+ {"dart:html_common", html_common_source_paths_, NULL, NULL, true},
+ {"dart:js", js_source_paths_, NULL, NULL, true},
+ {"dart:js_util", js_util_source_paths_, NULL, NULL, true},
+ {"dart:_blink", _blink_source_paths_, NULL, NULL, true},
+ {"dart:indexed_db", indexed_db_source_paths_, NULL, NULL, true},
+ {"cached_patches.dart", cached_patches_source_paths_, NULL, NULL, true},
+ {"dart:web_gl", web_gl_source_paths_, NULL, NULL, true},
+ {"metadata.dart", metadata_source_paths_, NULL, NULL, true},
+ {"dart:web_sql", web_sql_source_paths_, NULL, NULL, true},
+ {"dart:svg", svg_source_paths_, NULL, NULL, true},
+ {"dart:web_audio", web_audio_source_paths_, NULL, NULL, true},
#endif // defined(DART_NO_SNAPSHOT)
- // End marker.
- { NULL, NULL, NULL, NULL, false }
-};
+ // End marker.
+ {NULL, NULL, NULL, NULL, false}};
Dart_Port Builtin::load_port_ = ILLEGAL_PORT;
const int Builtin::num_libs_ =
@@ -100,8 +99,8 @@
if (!Dart_IsString(src)) {
// In case reading the file caused an error, use the sources directly.
const char* source = source_paths[i + 2];
- src = Dart_NewStringFromUTF8(
- reinterpret_cast<const uint8_t*>(source), strlen(source));
+ src = Dart_NewStringFromUTF8(reinterpret_cast<const uint8_t*>(source),
+ strlen(source));
}
return src;
}
@@ -127,8 +126,7 @@
}
if (builtin_libraries_[id].patch_url_ != NULL) {
ASSERT(builtin_libraries_[id].patch_paths_ != NULL);
- LoadPatchFiles(library,
- builtin_libraries_[id].patch_url_,
+ LoadPatchFiles(library, builtin_libraries_[id].patch_url_,
builtin_libraries_[id].patch_paths_);
}
return library;
diff --git a/runtime/bin/builtin.h b/runtime/bin/builtin.h
index f61316a..f42f2cf 100644
--- a/runtime/bin/builtin.h
+++ b/runtime/bin/builtin.h
@@ -17,8 +17,7 @@
namespace bin {
#define FUNCTION_NAME(name) Builtin_##name
-#define REGISTER_FUNCTION(name, count) \
- { ""#name, FUNCTION_NAME(name), count },
+#define REGISTER_FUNCTION(name, count) {"" #name, FUNCTION_NAME(name), count},
#define DECLARE_FUNCTION(name, count) \
extern void FUNCTION_NAME(name)(Dart_NativeArguments args);
diff --git a/runtime/bin/builtin_common.cc b/runtime/bin/builtin_common.cc
index 79713e1..064d004 100644
--- a/runtime/bin/builtin_common.cc
+++ b/runtime/bin/builtin_common.cc
@@ -27,9 +27,9 @@
Builtin::LoadAndCheckLibrary(Builtin::kBuiltinLibrary);
RETURN_IF_ERROR(builtin_lib);
// Set the _isolateId field.
- Dart_Handle result = Dart_SetField(builtin_lib,
- DartUtils::NewString("_isolateId"),
- Dart_NewInteger(Dart_GetMainPortId()));
+ Dart_Handle result =
+ Dart_SetField(builtin_lib, DartUtils::NewString("_isolateId"),
+ Dart_NewInteger(Dart_GetMainPortId()));
RETURN_IF_ERROR(result);
load_port_ = port;
ASSERT(load_port_ != ILLEGAL_PORT);
diff --git a/runtime/bin/builtin_gen_snapshot.cc b/runtime/bin/builtin_gen_snapshot.cc
index 17d4a57..8cf1d23 100644
--- a/runtime/bin/builtin_gen_snapshot.cc
+++ b/runtime/bin/builtin_gen_snapshot.cc
@@ -15,8 +15,7 @@
namespace bin {
// Lists the native function implementing basic logging facility.
-#define BUILTIN_NATIVE_LIST(V) \
- V(Builtin_PrintString, 1)
+#define BUILTIN_NATIVE_LIST(V) V(Builtin_PrintString, 1)
BUILTIN_NATIVE_LIST(DECLARE_FUNCTION);
@@ -24,9 +23,7 @@
const char* name_;
Dart_NativeFunction function_;
int argument_count_;
-} BuiltinEntries[] = {
- BUILTIN_NATIVE_LIST(REGISTER_FUNCTION)
-};
+} BuiltinEntries[] = {BUILTIN_NATIVE_LIST(REGISTER_FUNCTION)};
Dart_NativeFunction Builtin::NativeLookup(Dart_Handle name,
diff --git a/runtime/bin/builtin_in.cc b/runtime/bin/builtin_in.cc
index 45b2cbf..2fd818b 100644
--- a/runtime/bin/builtin_in.cc
+++ b/runtime/bin/builtin_in.cc
@@ -2,6 +2,8 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
+// clang-format off
+
#include "{{INCLUDE}}" // NOLINT
// This file is used to generate the mapping of standalone dart libraries
diff --git a/runtime/bin/builtin_natives.cc b/runtime/bin/builtin_natives.cc
index 874e442..394beb3 100644
--- a/runtime/bin/builtin_natives.cc
+++ b/runtime/bin/builtin_natives.cc
@@ -27,7 +27,7 @@
// using functions listed in io_natives.cc.
#define BUILTIN_NATIVE_LIST(V) \
V(Builtin_PrintString, 1) \
- V(Builtin_GetCurrentDirectory, 0) \
+ V(Builtin_GetCurrentDirectory, 0)
BUILTIN_NATIVE_LIST(DECLARE_FUNCTION);
@@ -36,9 +36,7 @@
const char* name_;
Dart_NativeFunction function_;
int argument_count_;
-} BuiltinEntries[] = {
- BUILTIN_NATIVE_LIST(REGISTER_FUNCTION)
-};
+} BuiltinEntries[] = {BUILTIN_NATIVE_LIST(REGISTER_FUNCTION)};
void Builtin_DummyNative(Dart_NativeArguments args) {
@@ -46,7 +44,6 @@
}
-
/**
* Looks up native functions in both libdart_builtin and libdart_io.
*/
@@ -106,10 +103,9 @@
fflush(stdout);
if (ShouldCaptureStdout()) {
// For now we report print output on the Stdout stream.
- uint8_t newline[] = { '\n' };
+ uint8_t newline[] = {'\n'};
Dart_ServiceSendDataEvent("Stdout", "WriteEvent", chars, length);
- Dart_ServiceSendDataEvent("Stdout", "WriteEvent",
- newline, sizeof(newline));
+ Dart_ServiceSendDataEvent("Stdout", "WriteEvent", newline, sizeof(newline));
}
}
diff --git a/runtime/bin/builtin_nolib.cc b/runtime/bin/builtin_nolib.cc
index 5ccf5c8..a61d915 100644
--- a/runtime/bin/builtin_nolib.cc
+++ b/runtime/bin/builtin_nolib.cc
@@ -14,13 +14,12 @@
namespace bin {
Builtin::builtin_lib_props Builtin::builtin_libraries_[] = {
- /* { url_, source_, patch_url_, patch_source_, has_natives_ } */
- { DartUtils::kBuiltinLibURL, NULL, NULL, NULL, true },
- { DartUtils::kIOLibURL, NULL, NULL, NULL, true },
+ /* { url_, source_, patch_url_, patch_source_, has_natives_ } */
+ {DartUtils::kBuiltinLibURL, NULL, NULL, NULL, true},
+ {DartUtils::kIOLibURL, NULL, NULL, NULL, true},
- // End marker.
- { NULL, NULL, NULL, NULL, false }
-};
+ // End marker.
+ {NULL, NULL, NULL, NULL, false}};
Dart_Port Builtin::load_port_ = ILLEGAL_PORT;
const int Builtin::num_libs_ =
@@ -33,14 +32,14 @@
Dart_Handle Builtin::PartSource(BuiltinLibraryId id, const char* uri) {
- return DartUtils::NewError(
- "Unreachable code in Builtin::PartSource (%d).", id);
+ return DartUtils::NewError("Unreachable code in Builtin::PartSource (%d).",
+ id);
}
Dart_Handle Builtin::GetSource(const char** source_paths, const char* uri) {
- return DartUtils::NewError(
- "Unreachable code in Builtin::GetSource (%s).", uri);
+ return DartUtils::NewError("Unreachable code in Builtin::GetSource (%s).",
+ uri);
}
@@ -60,8 +59,8 @@
Dart_Handle Builtin::LoadLibrary(Dart_Handle url, BuiltinLibraryId id) {
- return DartUtils::NewError(
- "Unreachable code in Builtin::LoadLibrary (%d).", id);
+ return DartUtils::NewError("Unreachable code in Builtin::LoadLibrary (%d).",
+ id);
}
diff --git a/runtime/bin/crypto.cc b/runtime/bin/crypto.cc
index ec4840f..24b5f2b 100644
--- a/runtime/bin/crypto.cc
+++ b/runtime/bin/crypto.cc
@@ -14,11 +14,11 @@
Dart_Handle count_obj = Dart_GetNativeArgument(args, 0);
const int64_t kMaxRandomBytes = 4096;
int64_t count64 = 0;
- if (!DartUtils::GetInt64Value(count_obj, &count64) ||
- (count64 < 0) || (count64 > kMaxRandomBytes)) {
- Dart_Handle error =
- DartUtils::NewString("Invalid argument: count must be a positive int "
- "less than or equal to 4096.");
+ if (!DartUtils::GetInt64Value(count_obj, &count64) || (count64 < 0) ||
+ (count64 > kMaxRandomBytes)) {
+ Dart_Handle error = DartUtils::NewString(
+ "Invalid argument: count must be a positive int "
+ "less than or equal to 4096.");
Dart_ThrowException(error);
}
intptr_t count = static_cast<intptr_t>(count64);
diff --git a/runtime/bin/crypto.h b/runtime/bin/crypto.h
index ccfb8fb..5e39404 100644
--- a/runtime/bin/crypto.h
+++ b/runtime/bin/crypto.h
@@ -24,4 +24,3 @@
} // namespace dart
#endif // RUNTIME_BIN_CRYPTO_H_
-
diff --git a/runtime/bin/crypto_android.cc b/runtime/bin/crypto_android.cc
index 7a970d0..b83a71b 100644
--- a/runtime/bin/crypto_android.cc
+++ b/runtime/bin/crypto_android.cc
@@ -17,8 +17,8 @@
bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
ThreadSignalBlocker signal_blocker(SIGPROF);
- intptr_t fd = TEMP_FAILURE_RETRY_NO_SIGNAL_BLOCKER(
- open("/dev/urandom", O_RDONLY));
+ intptr_t fd =
+ TEMP_FAILURE_RETRY_NO_SIGNAL_BLOCKER(open("/dev/urandom", O_RDONLY));
if (fd < 0) {
return false;
}
diff --git a/runtime/bin/crypto_fuchsia.cc b/runtime/bin/crypto_fuchsia.cc
index b4c84d0..a066574 100644
--- a/runtime/bin/crypto_fuchsia.cc
+++ b/runtime/bin/crypto_fuchsia.cc
@@ -17,8 +17,7 @@
while (read < count) {
const intptr_t remaining = count - read;
const intptr_t len =
- (MX_CPRNG_DRAW_MAX_LEN < remaining) ? MX_CPRNG_DRAW_MAX_LEN
- : remaining;
+ (MX_CPRNG_DRAW_MAX_LEN < remaining) ? MX_CPRNG_DRAW_MAX_LEN : remaining;
mx_size_t res = 0;
const mx_status_t status = mx_cprng_draw(buffer + read, len, &res);
if (status != NO_ERROR) {
diff --git a/runtime/bin/crypto_linux.cc b/runtime/bin/crypto_linux.cc
index c2e4ccd..b618101 100644
--- a/runtime/bin/crypto_linux.cc
+++ b/runtime/bin/crypto_linux.cc
@@ -17,8 +17,8 @@
bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
ThreadSignalBlocker signal_blocker(SIGPROF);
- intptr_t fd = TEMP_FAILURE_RETRY_NO_SIGNAL_BLOCKER(
- open("/dev/urandom", O_RDONLY));
+ intptr_t fd =
+ TEMP_FAILURE_RETRY_NO_SIGNAL_BLOCKER(open("/dev/urandom", O_RDONLY));
if (fd < 0) {
return false;
}
diff --git a/runtime/bin/crypto_macos.cc b/runtime/bin/crypto_macos.cc
index 7bea2ae..e2447c0 100644
--- a/runtime/bin/crypto_macos.cc
+++ b/runtime/bin/crypto_macos.cc
@@ -17,8 +17,8 @@
bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
ThreadSignalBlocker signal_blocker(SIGPROF);
- intptr_t fd = TEMP_FAILURE_RETRY_NO_SIGNAL_BLOCKER(
- open("/dev/urandom", O_RDONLY));
+ intptr_t fd =
+ TEMP_FAILURE_RETRY_NO_SIGNAL_BLOCKER(open("/dev/urandom", O_RDONLY));
if (fd < 0) {
return false;
}
diff --git a/runtime/bin/dartutils.cc b/runtime/bin/dartutils.cc
index ff8b53d..db8e1fa 100644
--- a/runtime/bin/dartutils.cc
+++ b/runtime/bin/dartutils.cc
@@ -56,8 +56,8 @@
};
-MagicNumberData snapshot_magic_number = { { 0xf5, 0xf5, 0xdc, 0xdc }, true };
-MagicNumberData kernel_magic_number = { {0x90, 0xab, 0xcd, 0xef}, false };
+MagicNumberData snapshot_magic_number = {{0xf5, 0xf5, 0xdc, 0xdc}, true};
+MagicNumberData kernel_magic_number = {{0x90, 0xab, 0xcd, 0xef}, false};
bool TryReadKernel(const char* script_uri,
@@ -74,7 +74,7 @@
if (*kernel_length > 0 && buffer != NULL) {
*kernel_file = buffer;
if (DartUtils::SniffForMagicNumber(&buffer, kernel_length) !=
- DartUtils::kKernelMagicNumber) {
+ DartUtils::kKernelMagicNumber) {
free(const_cast<uint8_t*>(buffer));
*kernel_file = NULL;
} else {
@@ -93,7 +93,7 @@
static bool IsWindowsHost() {
#if defined(TARGET_OS_WINDOWS)
return true;
-#else // defined(TARGET_OS_WINDOWS)
+#else // defined(TARGET_OS_WINDOWS)
return false;
#endif // defined(TARGET_OS_WINDOWS)
}
@@ -125,8 +125,9 @@
}
-int64_t DartUtils::GetInt64ValueCheckRange(
- Dart_Handle value_obj, int64_t lower, int64_t upper) {
+int64_t DartUtils::GetInt64ValueCheckRange(Dart_Handle value_obj,
+ int64_t lower,
+ int64_t upper) {
int64_t value = DartUtils::GetIntegerValue(value_obj);
if (value < lower || upper < value) {
Dart_PropagateError(Dart_NewApiError("Value outside expected range"));
@@ -183,8 +184,8 @@
Dart_Handle DartUtils::SetStringField(Dart_Handle handle,
- const char* name,
- const char* val) {
+ const char* name,
+ const char* val) {
return Dart_SetField(handle, NewString(name), NewString(val));
}
@@ -207,8 +208,8 @@
static const intptr_t kDartExtensionSchemeLen = strlen(kDartExtensionScheme);
// If the URL starts with "dartext:" then it is considered as a special
// extension library URL which is handled differently from other URLs.
- return
- (strncmp(url_name, kDartExtensionScheme, kDartExtensionSchemeLen) == 0);
+ return (strncmp(url_name, kDartExtensionScheme, kDartExtensionSchemeLen) ==
+ 0);
}
@@ -232,15 +233,23 @@
}
+char* DartUtils::DirName(const char* url) {
+ const char* slash = strrchr(url, File::PathSeparator()[0]);
+ if (slash == NULL) {
+ return strdup(url);
+ } else {
+ return StringUtils::StrNDup(url, slash - url + 1);
+ }
+}
+
+
void* DartUtils::OpenFile(const char* name, bool write) {
File* file = File::Open(name, write ? File::kWriteTruncate : File::kRead);
return reinterpret_cast<void*>(file);
}
-void DartUtils::ReadFile(const uint8_t** data,
- intptr_t* len,
- void* stream) {
+void DartUtils::ReadFile(const uint8_t** data, intptr_t* len, void* stream) {
ASSERT(data != NULL);
ASSERT(len != NULL);
ASSERT(stream != NULL);
@@ -284,7 +293,8 @@
}
-static Dart_Handle SingleArgDart_Invoke(Dart_Handle lib, const char* method,
+static Dart_Handle SingleArgDart_Invoke(Dart_Handle lib,
+ const char* method,
Dart_Handle arg) {
const int kNumArgs = 1;
Dart_Handle dart_args[kNumArgs];
@@ -330,7 +340,7 @@
return Dart_NewApiError(error_msg);
}
Dart_Handle str = Dart_NewStringFromUTF8(text_buffer, len);
- free(const_cast<uint8_t *>(text_buffer));
+ free(const_cast<uint8_t*>(text_buffer));
return str;
}
@@ -370,8 +380,7 @@
Dart_Handle dart_args[kNumArgs];
dart_args[0] = script_uri;
return Dart_Invoke(DartUtils::BuiltinLib(),
- NewString("_resolveInWorkingDirectory"),
- kNumArgs,
+ NewString("_resolveInWorkingDirectory"), kNumArgs,
dart_args);
}
@@ -380,10 +389,8 @@
const int kNumArgs = 1;
Dart_Handle dart_args[kNumArgs];
dart_args[0] = library_uri;
- return Dart_Invoke(DartUtils::BuiltinLib(),
- NewString("_libraryFilePath"),
- kNumArgs,
- dart_args);
+ return Dart_Invoke(DartUtils::BuiltinLib(), NewString("_libraryFilePath"),
+ kNumArgs, dart_args);
}
@@ -391,10 +398,8 @@
const int kNumArgs = 1;
Dart_Handle dart_args[kNumArgs];
dart_args[0] = url;
- return Dart_Invoke(DartUtils::BuiltinLib(),
- NewString("_resolveScriptUri"),
- kNumArgs,
- dart_args);
+ return Dart_Invoke(DartUtils::BuiltinLib(), NewString("_resolveScriptUri"),
+ kNumArgs, dart_args);
}
@@ -407,8 +412,7 @@
dart_args[1] = url;
dart_args[2] = library_url;
return Dart_Invoke(DartUtils::BuiltinLib(),
- DartUtils::NewString("_loadDataAsync"),
- kNumArgs,
+ DartUtils::NewString("_loadDataAsync"), kNumArgs,
dart_args);
}
@@ -445,17 +449,21 @@
if (tag == Dart_kImportTag) {
Builtin::BuiltinLibraryId id = Builtin::FindId(url_string);
if (id == Builtin::kInvalidLibrary) {
- return NewError("The built-in library '%s' is not available"
- " on the stand-alone VM.\n", url_string);
+ return NewError(
+ "The built-in library '%s' is not available"
+ " on the stand-alone VM.\n",
+ url_string);
}
return Builtin::LoadLibrary(url, id);
} else {
ASSERT(tag == Dart_kSourceTag);
Builtin::BuiltinLibraryId id = Builtin::FindId(library_url_string);
if (id == Builtin::kInvalidLibrary) {
- return NewError("The built-in library '%s' is not available"
- " on the stand-alone VM. Trying to load"
- " '%s'.\n", library_url_string, url_string);
+ return NewError(
+ "The built-in library '%s' is not available"
+ " on the stand-alone VM. Trying to load"
+ " '%s'.\n",
+ library_url_string, url_string);
}
// Prepend the library URI to form a unique script URI for the part.
intptr_t len = snprintf(NULL, 0, "%s/%s", library_url_string, url_string);
@@ -463,8 +471,7 @@
snprintf(part_uri, len + 1, "%s/%s", library_url_string, url_string);
Dart_Handle part_uri_obj = DartUtils::NewString(part_uri);
free(part_uri);
- return Dart_LoadSource(library,
- part_uri_obj, Dart_Null(),
+ return Dart_LoadSource(library, part_uri_obj, Dart_Null(),
Builtin::PartSource(id, url_string), 0, 0);
}
// All cases should have been handled above.
@@ -486,9 +493,7 @@
"Relative paths for dart extensions are not supported: '%s'",
extension_path);
}
- return Extensions::LoadExtension(lib_path_str,
- extension_path,
- library);
+ return Extensions::LoadExtension(lib_path_str, extension_path, library);
}
// Handle 'import' or 'part' requests for all other URIs. Call dart code to
@@ -513,7 +518,7 @@
DartUtils::MagicNumber DartUtils::SniffForMagicNumber(const uint8_t** buf,
- intptr_t* len) {
+ intptr_t* len) {
if (CheckMagicNumber(buf, len, snapshot_magic_number)) {
return kSnapshotMagicNumber;
}
@@ -528,18 +533,16 @@
void DartUtils::WriteMagicNumber(File* file) {
// Write a magic number and version information into the snapshot file.
- bool bytes_written = file->WriteFully(snapshot_magic_number.bytes,
- MagicNumberData::kLength);
+ bool bytes_written =
+ file->WriteFully(snapshot_magic_number.bytes, MagicNumberData::kLength);
ASSERT(bytes_written);
}
Dart_Handle DartUtils::LoadScript(const char* script_uri) {
- Dart_TimelineEvent("LoadScript",
- Dart_TimelineGetMicros(),
- Dart_GetMainPortId(),
- Dart_Timeline_Event_Async_Begin,
- 0, NULL, NULL);
+ Dart_TimelineEvent("LoadScript", Dart_TimelineGetMicros(),
+ Dart_GetMainPortId(), Dart_Timeline_Event_Async_Begin, 0,
+ NULL, NULL);
Dart_Handle uri = Dart_NewStringFromCString(script_uri);
return LoadDataAsync_Invoke(Dart_Null(), uri, Dart_Null());
}
@@ -561,8 +564,8 @@
bool is_service_isolate,
bool trace_loading) {
// Setup the internal library's 'internalPrint' function.
- Dart_Handle print = Dart_Invoke(
- builtin_lib, NewString("_getPrintClosure"), 0, NULL);
+ Dart_Handle print =
+ Dart_Invoke(builtin_lib, NewString("_getPrintClosure"), 0, NULL);
RETURN_IF_ERROR(print);
Dart_Handle result =
Dart_SetField(internal_lib, NewString("_printClosure"), print);
@@ -574,8 +577,8 @@
RETURN_IF_ERROR(result);
}
if (trace_loading) {
- result = Dart_SetField(builtin_lib,
- NewString("_traceLoading"), Dart_True());
+ result =
+ Dart_SetField(builtin_lib, NewString("_traceLoading"), Dart_True());
RETURN_IF_ERROR(result);
}
// Set current working directory.
@@ -591,12 +594,11 @@
bool is_service_isolate) {
if (!is_service_isolate) {
// Setup the 'Uri.base' getter in dart:core.
- Dart_Handle uri_base = Dart_Invoke(
- builtin_lib, NewString("_getUriBaseClosure"), 0, NULL);
+ Dart_Handle uri_base =
+ Dart_Invoke(builtin_lib, NewString("_getUriBaseClosure"), 0, NULL);
RETURN_IF_ERROR(uri_base);
- Dart_Handle result = Dart_SetField(core_lib,
- NewString("_uriBaseClosure"),
- uri_base);
+ Dart_Handle result =
+ Dart_SetField(core_lib, NewString("_uriBaseClosure"), uri_base);
RETURN_IF_ERROR(result);
}
return Dart_True();
@@ -605,14 +607,13 @@
Dart_Handle DartUtils::PrepareAsyncLibrary(Dart_Handle async_lib,
Dart_Handle isolate_lib) {
- Dart_Handle schedule_immediate_closure =
- Dart_Invoke(isolate_lib, NewString("_getIsolateScheduleImmediateClosure"),
- 0, NULL);
+ Dart_Handle schedule_immediate_closure = Dart_Invoke(
+ isolate_lib, NewString("_getIsolateScheduleImmediateClosure"), 0, NULL);
RETURN_IF_ERROR(schedule_immediate_closure);
Dart_Handle args[1];
args[0] = schedule_immediate_closure;
- return Dart_Invoke(
- async_lib, NewString("_setScheduleImmediateClosure"), 1, args);
+ return Dart_Invoke(async_lib, NewString("_setScheduleImmediateClosure"), 1,
+ args);
}
@@ -647,10 +648,8 @@
const int kNumArgs = 1;
Dart_Handle dart_args[kNumArgs];
dart_args[0] = result;
- result = Dart_Invoke(DartUtils::BuiltinLib(),
- NewString("_setPackageRoot"),
- kNumArgs,
- dart_args);
+ result = Dart_Invoke(DartUtils::BuiltinLib(), NewString("_setPackageRoot"),
+ kNumArgs, dart_args);
RETURN_IF_ERROR(result);
} else if (packages_config != NULL) {
Dart_Handle result = NewString(packages_config);
@@ -658,10 +657,8 @@
const int kNumArgs = 1;
Dart_Handle dart_args[kNumArgs];
dart_args[0] = result;
- result = Dart_Invoke(DartUtils::BuiltinLib(),
- NewString("_setPackagesMap"),
- kNumArgs,
- dart_args);
+ result = Dart_Invoke(DartUtils::BuiltinLib(), NewString("_setPackagesMap"),
+ kNumArgs, dart_args);
RETURN_IF_ERROR(result);
}
return Dart_True();
@@ -705,15 +702,13 @@
Dart_Handle result = Dart_FinalizeLoading(false);
RETURN_IF_ERROR(result);
- result = PrepareBuiltinLibrary(builtin_lib,
- internal_lib,
- is_service_isolate,
+ result = PrepareBuiltinLibrary(builtin_lib, internal_lib, is_service_isolate,
trace_loading);
RETURN_IF_ERROR(result);
RETURN_IF_ERROR(PrepareAsyncLibrary(async_lib, isolate_lib));
- RETURN_IF_ERROR(PrepareCoreLibrary(
- core_lib, builtin_lib, is_service_isolate));
+ RETURN_IF_ERROR(
+ PrepareCoreLibrary(core_lib, builtin_lib, is_service_isolate));
RETURN_IF_ERROR(PrepareIsolateLibrary(isolate_lib));
RETURN_IF_ERROR(PrepareIOLibrary(io_lib));
return result;
@@ -821,16 +816,12 @@
Dart_Handle DartUtils::NewDartArgumentError(const char* message) {
- return NewDartExceptionWithMessage(kCoreLibURL,
- "ArgumentError",
- message);
+ return NewDartExceptionWithMessage(kCoreLibURL, "ArgumentError", message);
}
Dart_Handle DartUtils::NewDartUnsupportedError(const char* message) {
- return NewDartExceptionWithMessage(kCoreLibURL,
- "UnsupportedError",
- message);
+ return NewDartExceptionWithMessage(kCoreLibURL, "UnsupportedError", message);
}
@@ -838,9 +829,7 @@
const char* message,
Dart_Handle os_error) {
// Create a dart:io exception object of the given type.
- return NewDartExceptionWithOSError(kIOLibURL,
- exception_name,
- message,
+ return NewDartExceptionWithOSError(kIOLibURL, exception_name, message,
os_error);
}
@@ -889,9 +878,9 @@
// objects. As these will be used by different threads the use of
// these depends on the fact that the marking internally in the
// Dart_CObject structure is not marking simple value objects.
-Dart_CObject CObject::api_null_ = { Dart_CObject_kNull , { 0 } };
-Dart_CObject CObject::api_true_ = { Dart_CObject_kBool , { true } };
-Dart_CObject CObject::api_false_ = { Dart_CObject_kBool, { false } };
+Dart_CObject CObject::api_null_ = {Dart_CObject_kNull, {0}};
+Dart_CObject CObject::api_true_ = {Dart_CObject_kBool, {true}};
+Dart_CObject CObject::api_false_ = {Dart_CObject_kBool, {false}};
CObject CObject::null_ = CObject(&api_null_);
CObject CObject::true_ = CObject(&api_true_);
CObject CObject::false_ = CObject(&api_false_);
@@ -948,9 +937,8 @@
static bool IsHexDigit(char c) {
- return (('0' <= c) && (c <= '9'))
- || (('A' <= c) && (c <= 'F'))
- || (('a' <= c) && (c <= 'f'));
+ return (('0' <= c) && (c <= '9')) || (('A' <= c) && (c <= 'F')) ||
+ (('a' <= c) && (c <= 'f'));
}
@@ -1120,7 +1108,7 @@
Dart_CObject* CObject::NewUint32Array(intptr_t length) {
- Dart_CObject* cobject = New(Dart_CObject_kTypedData, 4*length);
+ Dart_CObject* cobject = New(Dart_CObject_kTypedData, 4 * length);
cobject->value.as_typed_data.type = Dart_TypedData_kUint32;
cobject->value.as_typed_data.length = length;
cobject->value.as_typed_data.values = reinterpret_cast<uint8_t*>(cobject + 1);
@@ -1129,7 +1117,9 @@
Dart_CObject* CObject::NewExternalUint8Array(
- intptr_t length, uint8_t* data, void* peer,
+ intptr_t length,
+ uint8_t* data,
+ void* peer,
Dart_WeakPersistentHandleFinalizer callback) {
Dart_CObject* cobject = New(Dart_CObject_kExternalTypedData);
cobject->value.as_external_typed_data.type = Dart_TypedData_kUint8;
@@ -1150,17 +1140,15 @@
}
uint8_t* data = IOBuffer::Allocate(static_cast<intptr_t>(length));
ASSERT(data != NULL);
- return NewExternalUint8Array(
- static_cast<intptr_t>(length), data, data, IOBuffer::Finalizer);
+ return NewExternalUint8Array(static_cast<intptr_t>(length), data, data,
+ IOBuffer::Finalizer);
}
void CObject::FreeIOBufferData(Dart_CObject* cobject) {
ASSERT(cobject->type == Dart_CObject_kExternalTypedData);
cobject->value.as_external_typed_data.callback(
- NULL,
- NULL,
- cobject->value.as_external_typed_data.peer);
+ NULL, NULL, cobject->value.as_external_typed_data.peer);
cobject->value.as_external_typed_data.data = NULL;
}
diff --git a/runtime/bin/dartutils.h b/runtime/bin/dartutils.h
index c2ab3fb..9cbebf6 100644
--- a/runtime/bin/dartutils.h
+++ b/runtime/bin/dartutils.h
@@ -47,7 +47,7 @@
explicit CommandLineOptions(int max_count)
: count_(0), max_count_(max_count), arguments_(NULL) {
static const int kWordSize = sizeof(intptr_t);
- arguments_ = reinterpret_cast<const char **>(malloc(max_count * kWordSize));
+ arguments_ = reinterpret_cast<const char**>(malloc(max_count * kWordSize));
if (arguments_ == NULL) {
max_count_ = 0;
}
@@ -95,8 +95,9 @@
// Returns the integer value of a Dart object. If the object is not
// an integer value or outside the requested range an API error is
// propagated.
- static int64_t GetInt64ValueCheckRange(
- Dart_Handle value_obj, int64_t lower, int64_t upper);
+ static int64_t GetInt64ValueCheckRange(Dart_Handle value_obj,
+ int64_t lower,
+ int64_t upper);
// Returns the intptr_t value of a Dart object. If the object is not
// an integer value or the value is outside the intptr_t range an
// API error is propagated.
@@ -125,6 +126,7 @@
static bool IsDartBuiltinLibURL(const char* url_name);
static bool IsHttpSchemeURL(const char* url_name);
static const char* RemoveScheme(const char* url);
+ static char* DirName(const char* url);
static void* MapExecutable(const char* name, intptr_t* file_len);
static void* OpenFile(const char* name, bool write);
static void ReadFile(const uint8_t** data, intptr_t* file_len, void* stream);
@@ -177,8 +179,8 @@
// Allocate length bytes for a C string with Dart_ScopeAllocate.
static char* ScopedCString(intptr_t length) {
char* result = NULL;
- result = reinterpret_cast<char*>(
- Dart_ScopeAllocate(length * sizeof(*result)));
+ result =
+ reinterpret_cast<char*>(Dart_ScopeAllocate(length * sizeof(*result)));
return result;
}
@@ -256,10 +258,10 @@
bool is_service_isolate,
bool trace_loading);
static Dart_Handle PrepareCoreLibrary(Dart_Handle core_lib,
- Dart_Handle builtin_lib,
- bool is_service_isolate);
+ Dart_Handle builtin_lib,
+ bool is_service_isolate);
static Dart_Handle PrepareAsyncLibrary(Dart_Handle async_lib,
- Dart_Handle isolate_lib);
+ Dart_Handle isolate_lib);
static Dart_Handle PrepareIOLibrary(Dart_Handle io_lib);
static Dart_Handle PrepareIsolateLibrary(Dart_Handle isolate_lib);
@@ -276,7 +278,7 @@
static const int kOSError = 2;
static const int kFileClosedError = 3;
- explicit CObject(Dart_CObject *cobject) : cobject_(cobject) {}
+ explicit CObject(Dart_CObject* cobject) : cobject_(cobject) {}
Dart_CObject_Type type() { return cobject_->type; }
Dart_TypedData_Type byte_array_type() {
ASSERT(type() == Dart_CObject_kTypedData ||
@@ -309,9 +311,7 @@
return type() == Dart_CObject_kBool && !cobject_->value.as_bool;
}
- void* operator new(size_t size) {
- return Dart_ScopeAllocate(size);
- }
+ void* operator new(size_t size) { return Dart_ScopeAllocate(size); }
static CObject* Null();
static CObject* True();
@@ -329,7 +329,9 @@
static Dart_CObject* NewUint8Array(intptr_t length);
static Dart_CObject* NewUint32Array(intptr_t length);
static Dart_CObject* NewExternalUint8Array(
- intptr_t length, uint8_t* data, void* peer,
+ intptr_t length,
+ uint8_t* data,
+ void* peer,
Dart_WeakPersistentHandleFinalizer callback);
static Dart_CObject* NewIOBuffer(int64_t length);
@@ -366,7 +368,7 @@
#define DECLARE_COBJECT_CONSTRUCTORS(t) \
- explicit CObject##t(Dart_CObject *cobject) : CObject(cobject) { \
+ explicit CObject##t(Dart_CObject* cobject) : CObject(cobject) { \
ASSERT(type() == Dart_CObject_k##t); \
cobject_ = cobject; \
} \
@@ -374,11 +376,11 @@
ASSERT(cobject != NULL); \
ASSERT(cobject->type() == Dart_CObject_k##t); \
cobject_ = cobject->AsApiCObject(); \
- } \
+ }
#define DECLARE_COBJECT_TYPED_DATA_CONSTRUCTORS(t) \
- explicit CObject##t##Array(Dart_CObject *cobject) : CObject(cobject) { \
+ explicit CObject##t##Array(Dart_CObject* cobject) : CObject(cobject) { \
ASSERT(type() == Dart_CObject_kTypedData); \
ASSERT(byte_array_type() == Dart_TypedData_k##t); \
cobject_ = cobject; \
@@ -388,11 +390,11 @@
ASSERT(cobject->type() == Dart_CObject_kTypedData); \
ASSERT(cobject->byte_array_type() == Dart_TypedData_k##t); \
cobject_ = cobject->AsApiCObject(); \
- } \
+ }
#define DECLARE_COBJECT_EXTERNAL_TYPED_DATA_CONSTRUCTORS(t) \
- explicit CObjectExternal##t##Array(Dart_CObject *cobject) \
+ explicit CObjectExternal##t##Array(Dart_CObject* cobject) \
: CObject(cobject) { \
ASSERT(type() == Dart_CObject_kExternalTypedData); \
ASSERT(byte_array_type() == Dart_TypedData_k##t); \
@@ -403,7 +405,7 @@
ASSERT(cobject->type() == Dart_CObject_kExternalTypedData); \
ASSERT(cobject->byte_array_type() == Dart_TypedData_k##t); \
cobject_ = cobject->AsApiCObject(); \
- } \
+ }
class CObjectBool : public CObject {
@@ -441,7 +443,7 @@
class CObjectIntptr : public CObject {
public:
- explicit CObjectIntptr(Dart_CObject *cobject) : CObject(cobject) {
+ explicit CObjectIntptr(Dart_CObject* cobject) : CObject(cobject) {
ASSERT(type() == Dart_CObject_kInt32 || type() == Dart_CObject_kInt64);
cobject_ = cobject;
}
@@ -452,7 +454,7 @@
cobject_ = cobject->AsApiCObject();
}
- intptr_t Value() {
+ intptr_t Value() {
intptr_t result;
if (type() == Dart_CObject_kInt32) {
result = cobject_->value.as_int32;
@@ -471,7 +473,7 @@
class CObjectBigint : public CObject {
public:
// DECLARE_COBJECT_CONSTRUCTORS(Bigint) would miss hex_value_ initialization.
- explicit CObjectBigint(Dart_CObject *cobject) : CObject(cobject) {
+ explicit CObjectBigint(Dart_CObject* cobject) : CObject(cobject) {
ASSERT(type() == Dart_CObject_kBigint);
cobject_ = cobject;
hex_value_ = NULL;
@@ -491,9 +493,7 @@
return hex_value_;
}
- ~CObjectBigint() {
- free(hex_value_);
- }
+ ~CObjectBigint() { free(hex_value_); }
private:
char* hex_value_;
@@ -555,7 +555,7 @@
class CObjectTypedData : public CObject {
public:
- explicit CObjectTypedData(Dart_CObject *cobject) : CObject(cobject) {
+ explicit CObjectTypedData(Dart_CObject* cobject) : CObject(cobject) {
ASSERT(type() == Dart_CObject_kTypedData);
cobject_ = cobject;
}
@@ -611,13 +611,9 @@
class ScopedBlockingCall {
public:
- ScopedBlockingCall() {
- Dart_ThreadDisableProfiling();
- }
+ ScopedBlockingCall() { Dart_ThreadDisableProfiling(); }
- ~ScopedBlockingCall() {
- Dart_ThreadEnableProfiling();
- }
+ ~ScopedBlockingCall() { Dart_ThreadEnableProfiling(); }
private:
DISALLOW_ALLOCATION();
@@ -635,8 +631,8 @@
public:
explicit ScopedMemBuffer(Dart_Handle object) {
if (!Dart_IsTypedData(object) && !Dart_IsList(object)) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Argument is not a List<int>"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Argument is not a List<int>"));
}
uint8_t* bytes = NULL;
@@ -646,10 +642,7 @@
is_typed_data = true;
Dart_TypedData_Type typ;
ThrowIfError(Dart_TypedDataAcquireData(
- object,
- &typ,
- reinterpret_cast<void**>(&bytes),
- &bytes_len));
+ object, &typ, reinterpret_cast<void**>(&bytes), &bytes_len));
} else {
ASSERT(Dart_IsList(object));
ThrowIfError(Dart_ListLength(object, &bytes_len));
diff --git a/runtime/bin/directory.cc b/runtime/bin/directory.cc
index ccf5918..3997a32d 100644
--- a/runtime/bin/directory.cc
+++ b/runtime/bin/directory.cc
@@ -79,12 +79,12 @@
void FUNCTION_NAME(Directory_CreateTemp)(Dart_NativeArguments args) {
Dart_Handle path = Dart_GetNativeArgument(args, 0);
if (!Dart_IsString(path)) {
- Dart_SetReturnValue(args, DartUtils::NewDartArgumentError(
- "Prefix argument of CreateSystemTempSync is not a String"));
+ Dart_SetReturnValue(
+ args, DartUtils::NewDartArgumentError(
+ "Prefix argument of CreateSystemTempSync is not a String"));
return;
}
- const char* result =
- Directory::CreateTemp(DartUtils::GetStringValue(path));
+ const char* result = Directory::CreateTemp(DartUtils::GetStringValue(path));
if (result != NULL) {
Dart_SetReturnValue(args, DartUtils::NewString(result));
} else {
@@ -126,8 +126,7 @@
Dart_Handle follow_links = Dart_GetNativeArgument(args, 3);
// Pass the list that should hold the directory listing to the
// SyncDirectoryListing object, which adds elements to it.
- SyncDirectoryListing sync_listing(results,
- DartUtils::GetStringValue(path),
+ SyncDirectoryListing sync_listing(results, DartUtils::GetStringValue(path),
DartUtils::GetBooleanValue(recursive),
DartUtils::GetBooleanValue(follow_links));
Directory::List(&sync_listing);
@@ -142,10 +141,9 @@
AsyncDirectoryListing* listing;
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
ASSERT(Dart_IsInstance(dart_this));
- ThrowIfError(Dart_GetNativeInstanceField(
- dart_this,
- kAsyncDirectoryListerFieldIndex,
- reinterpret_cast<intptr_t*>(&listing)));
+ ThrowIfError(
+ Dart_GetNativeInstanceField(dart_this, kAsyncDirectoryListerFieldIndex,
+ reinterpret_cast<intptr_t*>(&listing)));
if (listing != NULL) {
intptr_t listing_pointer = reinterpret_cast<intptr_t>(listing);
// Increment the listing's reference count. This native should only be
@@ -173,15 +171,10 @@
DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 1));
AsyncDirectoryListing* listing =
reinterpret_cast<AsyncDirectoryListing*>(listing_pointer);
- Dart_NewWeakPersistentHandle(
- dart_this,
- reinterpret_cast<void*>(listing),
- sizeof(*listing),
- ReleaseListing);
+ Dart_NewWeakPersistentHandle(dart_this, reinterpret_cast<void*>(listing),
+ sizeof(*listing), ReleaseListing);
Dart_Handle result = Dart_SetNativeInstanceField(
- dart_this,
- kAsyncDirectoryListerFieldIndex,
- listing_pointer);
+ dart_this, kAsyncDirectoryListerFieldIndex, listing_pointer);
if (Dart_IsError(result)) {
Log::PrintErr("SetAsyncDirectoryListerPointer failed\n");
Dart_PropagateError(result);
@@ -214,8 +207,8 @@
CObject* Directory::DeleteRequest(const CObjectArray& request) {
- if ((request.Length() == 2) &&
- request[0]->IsString() && request[1]->IsBool()) {
+ if ((request.Length() == 2) && request[0]->IsString() &&
+ request[1]->IsBool()) {
CObjectString path(request[0]);
CObjectBool recursive(request[1]);
if (Directory::Delete(path.CString(), recursive.Value())) {
@@ -265,7 +258,7 @@
// Respond with an illegal argument list error message.
CObjectArray* error = new CObjectArray(CObject::NewArray(3));
error->SetAt(0, new CObjectInt32(
- CObject::NewInt32(AsyncDirectoryListing::kListError)));
+ CObject::NewInt32(AsyncDirectoryListing::kListError)));
error->SetAt(1, CObject::Null());
error->SetAt(2, CObject::IllegalArgumentError());
return error;
@@ -273,31 +266,27 @@
CObject* Directory::ListStartRequest(const CObjectArray& request) {
- if ((request.Length() == 3) &&
- request[0]->IsString() &&
- request[1]->IsBool() &&
- request[2]->IsBool()) {
+ if ((request.Length() == 3) && request[0]->IsString() &&
+ request[1]->IsBool() && request[2]->IsBool()) {
CObjectString path(request[0]);
CObjectBool recursive(request[1]);
CObjectBool follow_links(request[2]);
- AsyncDirectoryListing* dir_listing =
- new AsyncDirectoryListing(path.CString(),
- recursive.Value(),
- follow_links.Value());
+ AsyncDirectoryListing* dir_listing = new AsyncDirectoryListing(
+ path.CString(), recursive.Value(), follow_links.Value());
if (dir_listing->error()) {
// Report error now, so we capture the correct OSError.
CObject* err = CObject::NewOSError();
dir_listing->Release();
CObjectArray* error = new CObjectArray(CObject::NewArray(3));
- error->SetAt(0, new CObjectInt32(
- CObject::NewInt32(AsyncDirectoryListing::kListError)));
+ error->SetAt(0, new CObjectInt32(CObject::NewInt32(
+ AsyncDirectoryListing::kListError)));
error->SetAt(1, request[0]);
error->SetAt(2, err);
return error;
}
// TODO(ajohnsen): Consider returning the first few results.
- return new CObjectIntptr(CObject::NewIntptr(
- reinterpret_cast<intptr_t>(dir_listing)));
+ return new CObjectIntptr(
+ CObject::NewIntptr(reinterpret_cast<intptr_t>(dir_listing)));
}
return CreateIllegalArgumentError();
}
@@ -346,8 +335,7 @@
CObject* Directory::RenameRequest(const CObjectArray& request) {
- if ((request.Length() == 2) &&
- request[0]->IsString() &&
+ if ((request.Length() == 2) && request[0]->IsString() &&
request[1]->IsString()) {
CObjectString path(request[0]);
CObjectString new_path(request[1]);
@@ -401,7 +389,7 @@
// Delay calling CurrentPath() until after CObject::NewOSError() in case
// CurrentPath() pollutes the OS error code.
response->SetAt(1, new CObjectString(CObject::NewString(
- error() ? "Invalid path" : CurrentPath())));
+ error() ? "Invalid path" : CurrentPath())));
response->SetAt(2, err);
array_->SetAt(index_++, response);
return index_ < length_;
@@ -410,8 +398,7 @@
bool SyncDirectoryListing::HandleDirectory(const char* dir_name) {
Dart_Handle dir_name_dart = DartUtils::NewString(dir_name);
- Dart_Handle dir =
- Dart_New(directory_type_, Dart_Null(), 1, &dir_name_dart);
+ Dart_Handle dir = Dart_New(directory_type_, Dart_Null(), 1, &dir_name_dart);
Dart_Handle result = Dart_Invoke(results_, add_string_, 1, &dir);
if (Dart_IsError(result)) {
Dart_PropagateError(result);
@@ -422,8 +409,7 @@
bool SyncDirectoryListing::HandleLink(const char* link_name) {
Dart_Handle link_name_dart = DartUtils::NewString(link_name);
- Dart_Handle link =
- Dart_New(link_type_, Dart_Null(), 1, &link_name_dart);
+ Dart_Handle link = Dart_New(link_type_, Dart_Null(), 1, &link_name_dart);
Dart_Handle result = Dart_Invoke(results_, add_string_, 1, &link);
if (Dart_IsError(result)) {
Dart_PropagateError(result);
@@ -434,8 +420,7 @@
bool SyncDirectoryListing::HandleFile(const char* file_name) {
Dart_Handle file_name_dart = DartUtils::NewString(file_name);
- Dart_Handle file =
- Dart_New(file_type_, Dart_Null(), 1, &file_name_dart);
+ Dart_Handle file = Dart_New(file_type_, Dart_Null(), 1, &file_name_dart);
Dart_Handle result = Dart_Invoke(results_, add_string_, 1, &file);
if (Dart_IsError(result)) {
Dart_PropagateError(result);
@@ -452,9 +437,7 @@
args[2] = dart_os_error;
Dart_ThrowException(Dart_New(
DartUtils::GetDartType(DartUtils::kIOLibURL, "FileSystemException"),
- Dart_Null(),
- 3,
- args));
+ Dart_Null(), 3, args));
return true;
}
@@ -497,7 +480,8 @@
listing->HandleError();
listing->HandleDone();
} else {
- while (ListNext(listing)) {}
+ while (ListNext(listing)) {
+ }
}
}
diff --git a/runtime/bin/directory.h b/runtime/bin/directory.h
index a15e6ad..86026b7 100644
--- a/runtime/bin/directory.h
+++ b/runtime/bin/directory.h
@@ -38,9 +38,7 @@
void Reset(intptr_t new_length);
- intptr_t length() const {
- return length_;
- }
+ intptr_t length() const { return length_; }
private:
void* data_;
@@ -64,23 +62,17 @@
class DirectoryListingEntry {
public:
explicit DirectoryListingEntry(DirectoryListingEntry* parent)
- : parent_(parent), lister_(0), done_(false), link_(NULL) {}
+ : parent_(parent), lister_(0), done_(false), link_(NULL) {}
~DirectoryListingEntry();
ListType Next(DirectoryListing* listing);
- DirectoryListingEntry* parent() const {
- return parent_;
- }
+ DirectoryListingEntry* parent() const { return parent_; }
- LinkList* link() {
- return link_;
- }
+ LinkList* link() { return link_; }
- void set_link(LinkList* link) {
- link_ = link;
- }
+ void set_link(LinkList* link) { link_ = link; }
void ResetLink();
@@ -97,19 +89,17 @@
class DirectoryListing {
public:
DirectoryListing(const char* dir_name, bool recursive, bool follow_links)
- : top_(NULL),
- error_(false),
- recursive_(recursive),
- follow_links_(follow_links) {
+ : top_(NULL),
+ error_(false),
+ recursive_(recursive),
+ follow_links_(follow_links) {
if (!path_buffer_.Add(dir_name)) {
error_ = true;
}
Push(new DirectoryListingEntry(NULL));
}
- virtual ~DirectoryListing() {
- PopAll();
- }
+ virtual ~DirectoryListing() { PopAll(); }
virtual bool HandleDirectory(const char* dir_name) = 0;
virtual bool HandleFile(const char* file_name) = 0;
@@ -117,9 +107,7 @@
virtual bool HandleError() = 0;
virtual void HandleDone() {}
- void Push(DirectoryListingEntry* directory) {
- top_ = directory;
- }
+ void Push(DirectoryListingEntry* directory) { top_ = directory; }
void Pop() {
ASSERT(!IsEmpty());
@@ -128,9 +116,7 @@
delete current;
}
- bool IsEmpty() const {
- return top_ == NULL;
- }
+ bool IsEmpty() const { return top_ == NULL; }
void PopAll() {
while (!IsEmpty()) {
@@ -138,29 +124,17 @@
}
}
- DirectoryListingEntry* top() const {
- return top_;
- }
+ DirectoryListingEntry* top() const { return top_; }
- bool recursive() const {
- return recursive_;
- }
+ bool recursive() const { return recursive_; }
- bool follow_links() const {
- return follow_links_;
- }
+ bool follow_links() const { return follow_links_; }
- const char* CurrentPath() {
- return path_buffer_.AsScopedString();
- }
+ const char* CurrentPath() { return path_buffer_.AsScopedString(); }
- PathBuffer& path_buffer() {
- return path_buffer_;
- }
+ PathBuffer& path_buffer() { return path_buffer_; }
- bool error() const {
- return error_;
- }
+ bool error() const { return error_; }
private:
PathBuffer path_buffer_;
@@ -182,9 +156,7 @@
kListDone = 4
};
- AsyncDirectoryListing(const char* dir_name,
- bool recursive,
- bool follow_links)
+ AsyncDirectoryListing(const char* dir_name, bool recursive, bool follow_links)
: ReferenceCounted(),
DirectoryListing(dir_name, recursive, follow_links),
array_(NULL),
@@ -204,9 +176,7 @@
length_ = length;
}
- intptr_t index() const {
- return index_;
- }
+ intptr_t index() const { return index_; }
private:
virtual ~AsyncDirectoryListing() {}
@@ -220,21 +190,17 @@
};
-class SyncDirectoryListing: public DirectoryListing {
+class SyncDirectoryListing : public DirectoryListing {
public:
SyncDirectoryListing(Dart_Handle results,
const char* dir_name,
bool recursive,
bool follow_links)
- : DirectoryListing(dir_name, recursive, follow_links),
- results_(results) {
+ : DirectoryListing(dir_name, recursive, follow_links), results_(results) {
add_string_ = DartUtils::NewString("add");
- directory_type_ =
- DartUtils::GetDartType(DartUtils::kIOLibURL, "Directory");
- file_type_ =
- DartUtils::GetDartType(DartUtils::kIOLibURL, "File");
- link_type_ =
- DartUtils::GetDartType(DartUtils::kIOLibURL, "Link");
+ directory_type_ = DartUtils::GetDartType(DartUtils::kIOLibURL, "Directory");
+ file_type_ = DartUtils::GetDartType(DartUtils::kIOLibURL, "File");
+ link_type_ = DartUtils::GetDartType(DartUtils::kIOLibURL, "Link");
}
virtual ~SyncDirectoryListing() {}
virtual bool HandleDirectory(const char* dir_name);
@@ -256,11 +222,7 @@
class Directory {
public:
- enum ExistsResult {
- UNKNOWN,
- EXISTS,
- DOES_NOT_EXIST
- };
+ enum ExistsResult { UNKNOWN, EXISTS, DOES_NOT_EXIST };
static void List(DirectoryListing* listing);
static ExistsResult Exists(const char* path);
diff --git a/runtime/bin/directory_android.cc b/runtime/bin/directory_android.cc
index 75ca974..e61d513 100644
--- a/runtime/bin/directory_android.cc
+++ b/runtime/bin/directory_android.cc
@@ -7,12 +7,12 @@
#include "bin/directory.h"
-#include <dirent.h> // NOLINT
-#include <errno.h> // NOLINT
-#include <string.h> // NOLINT
+#include <dirent.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <string.h> // NOLINT
#include <sys/param.h> // NOLINT
-#include <sys/stat.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <sys/stat.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/dartutils.h"
#include "bin/file.h"
@@ -56,13 +56,9 @@
bool PathBuffer::Add(const char* name) {
char* data = AsString();
- int written = snprintf(data + length_,
- PATH_MAX - length_,
- "%s",
- name);
+ int written = snprintf(data + length_, PATH_MAX - length_, "%s", name);
data[PATH_MAX] = '\0';
- if ((written <= PATH_MAX - length_) &&
- (written >= 0) &&
+ if ((written <= PATH_MAX - length_) && (written >= 0) &&
(static_cast<size_t>(written) == strnlen(name, PATH_MAX + 1))) {
length_ += written;
return true;
@@ -119,8 +115,8 @@
int status = 0;
dirent entry;
dirent* result;
- status = NO_RETRY_EXPECTED(readdir_r(
- reinterpret_cast<DIR*>(lister_), &entry, &result));
+ status = NO_RETRY_EXPECTED(
+ readdir_r(reinterpret_cast<DIR*>(lister_), &entry, &result));
if ((status == 0) && (result != NULL)) {
if (!listing->path_buffer().Add(entry.d_name)) {
done_ = true;
@@ -139,8 +135,8 @@
if (!listing->follow_links()) {
return kListLink;
}
- // Else fall through to next case.
- // Fall through.
+ // Else fall through to next case.
+ // Fall through.
case DT_UNKNOWN: {
// On some file systems the entry type is not determined by
// readdir_r. For those and for links we use stat to determine
@@ -155,9 +151,7 @@
}
if (listing->follow_links() && S_ISLNK(entry_info.st_mode)) {
// Check to see if we are in a loop created by a symbolic link.
- LinkList current_link = { entry_info.st_dev,
- entry_info.st_ino,
- link_ };
+ LinkList current_link = {entry_info.st_dev, entry_info.st_ino, link_};
LinkList* previous = link_;
while (previous != NULL) {
if ((previous->dev == current_link.dev) &&
@@ -234,14 +228,12 @@
static bool DeleteRecursively(PathBuffer* path);
-static bool DeleteFile(char* file_name,
- PathBuffer* path) {
+static bool DeleteFile(char* file_name, PathBuffer* path) {
return path->Add(file_name) && (unlink(path->AsString()) == 0);
}
-static bool DeleteDir(char* dir_name,
- PathBuffer* path) {
+static bool DeleteDir(char* dir_name, PathBuffer* path) {
if ((strcmp(dir_name, ".") == 0) || (strcmp(dir_name, "..") == 0)) {
return true;
}
@@ -281,7 +273,7 @@
if (result == NULL) {
// End of directory.
return NO_RETRY_EXPECTED(closedir(dir_pointer)) == 0 &&
- NO_RETRY_EXPECTED(remove(path->AsString())) == 0;
+ NO_RETRY_EXPECTED(remove(path->AsString())) == 0;
}
bool ok = false;
switch (entry.d_type) {
@@ -344,19 +336,14 @@
return DOES_NOT_EXIST;
}
} else {
- if ((errno == EACCES) ||
- (errno == EBADF) ||
- (errno == EFAULT) ||
- (errno == ENOMEM) ||
- (errno == EOVERFLOW)) {
+ if ((errno == EACCES) || (errno == EBADF) || (errno == EFAULT) ||
+ (errno == ENOMEM) || (errno == EOVERFLOW)) {
// Search permissions denied for one of the directories in the
// path or a low level error occured. We do not know if the
// directory exists.
return UNKNOWN;
}
- ASSERT((errno == ELOOP) ||
- (errno == ENAMETOOLONG) ||
- (errno == ENOENT) ||
+ ASSERT((errno == ELOOP) || (errno == ENAMETOOLONG) || (errno == ENOENT) ||
(errno == ENOTDIR));
return DOES_NOT_EXIST;
}
@@ -406,13 +393,13 @@
if (Directory::system_temp_path_override_ != NULL) {
return DartUtils::ScopedCopyCString(Directory::system_temp_path_override_);
}
- // Android does not have a /tmp directory. A partial substitute,
- // suitable for bring-up work and tests, is to create a tmp
- // directory in /data/local/tmp.
- //
- // TODO(4413): In the long run, when running in an application we should
- // probably use the appropriate directory from the Android API,
- // probably what File.createTempFile uses.
+// Android does not have a /tmp directory. A partial substitute,
+// suitable for bring-up work and tests, is to create a tmp
+// directory in /data/local/tmp.
+//
+// TODO(4413): In the long run, when running in an application we should
+// probably use the appropriate directory from the Android API,
+// probably what File.createTempFile uses.
#define ANDROID_TEMP_DIR "/data/local/tmp"
struct stat st;
if (stat(ANDROID_TEMP_DIR, &st) != 0) {
diff --git a/runtime/bin/directory_fuchsia.cc b/runtime/bin/directory_fuchsia.cc
index 1593ff7..5223cb0 100644
--- a/runtime/bin/directory_fuchsia.cc
+++ b/runtime/bin/directory_fuchsia.cc
@@ -7,11 +7,11 @@
#include "bin/directory.h"
-#include <errno.h> // NOLINT
-#include <stdlib.h> // NOLINT
-#include <string.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <stdlib.h> // NOLINT
+#include <string.h> // NOLINT
#include <sys/stat.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/dartutils.h"
#include "bin/file.h"
@@ -60,13 +60,9 @@
return false;
}
char* data = AsString();
- int written = snprintf(data + length_,
- PATH_MAX - length_,
- "%s",
- name);
+ int written = snprintf(data + length_, PATH_MAX - length_, "%s", name);
data[PATH_MAX] = '\0';
- if ((written <= (PATH_MAX - length_)) &&
- (written > 0) &&
+ if ((written <= (PATH_MAX - length_)) && (written > 0) &&
(static_cast<size_t>(written) == strnlen(name, PATH_MAX + 1))) {
length_ += written;
return true;
@@ -109,19 +105,14 @@
return DOES_NOT_EXIST;
}
} else {
- if ((errno == EACCES) ||
- (errno == EBADF) ||
- (errno == EFAULT) ||
- (errno == ENOMEM) ||
- (errno == EOVERFLOW)) {
+ if ((errno == EACCES) || (errno == EBADF) || (errno == EFAULT) ||
+ (errno == ENOMEM) || (errno == EOVERFLOW)) {
// Search permissions denied for one of the directories in the
// path or a low level error occured. We do not know if the
// directory exists.
return UNKNOWN;
}
- ASSERT((errno == ELOOP) ||
- (errno == ENAMETOOLONG) ||
- (errno == ENOENT) ||
+ ASSERT((errno == ELOOP) || (errno == ENAMETOOLONG) || (errno == ENOENT) ||
(errno == ENOTDIR));
return DOES_NOT_EXIST;
}
diff --git a/runtime/bin/directory_linux.cc b/runtime/bin/directory_linux.cc
index 2f2e6b0..43ee548 100644
--- a/runtime/bin/directory_linux.cc
+++ b/runtime/bin/directory_linux.cc
@@ -7,13 +7,13 @@
#include "bin/directory.h"
-#include <dirent.h> // NOLINT
-#include <errno.h> // NOLINT
-#include <stdlib.h> // NOLINT
-#include <string.h> // NOLINT
+#include <dirent.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <stdlib.h> // NOLINT
+#include <string.h> // NOLINT
#include <sys/param.h> // NOLINT
-#include <sys/stat.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <sys/stat.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/dartutils.h"
#include "bin/file.h"
@@ -57,13 +57,9 @@
bool PathBuffer::Add(const char* name) {
char* data = AsString();
- int written = snprintf(data + length_,
- PATH_MAX - length_,
- "%s",
- name);
+ int written = snprintf(data + length_, PATH_MAX - length_, "%s", name);
data[PATH_MAX] = '\0';
- if ((written <= PATH_MAX - length_) &&
- (written >= 0) &&
+ if ((written <= PATH_MAX - length_) && (written >= 0) &&
(static_cast<size_t>(written) == strnlen(name, PATH_MAX + 1))) {
length_ += written;
return true;
@@ -137,8 +133,8 @@
if (!listing->follow_links()) {
return kListLink;
}
- // Else fall through to next case.
- // Fall through.
+ // Else fall through to next case.
+ // Fall through.
case DT_UNKNOWN: {
// On some file systems the entry type is not determined by
// readdir. For those and for links we use stat to determine
@@ -153,9 +149,7 @@
}
if (listing->follow_links() && S_ISLNK(entry_info.st_mode)) {
// Check to see if we are in a loop created by a symbolic link.
- LinkList current_link = { entry_info.st_dev,
- entry_info.st_ino,
- link_ };
+ LinkList current_link = {entry_info.st_dev, entry_info.st_ino, link_};
LinkList* previous = link_;
while (previous != NULL) {
if ((previous->dev == current_link.dev) &&
@@ -231,15 +225,13 @@
static bool DeleteRecursively(PathBuffer* path);
-static bool DeleteFile(char* file_name,
- PathBuffer* path) {
+static bool DeleteFile(char* file_name, PathBuffer* path) {
return path->Add(file_name) &&
- (NO_RETRY_EXPECTED(unlink(path->AsString())) == 0);
+ (NO_RETRY_EXPECTED(unlink(path->AsString())) == 0);
}
-static bool DeleteDir(char* dir_name,
- PathBuffer* path) {
+static bool DeleteDir(char* dir_name, PathBuffer* path) {
if ((strcmp(dir_name, ".") == 0) || (strcmp(dir_name, "..") == 0)) {
return true;
}
@@ -273,24 +265,20 @@
// Iterate the directory and delete all files and directories.
int path_length = path->length();
- while (true){
- // In case `readdir()` returns `NULL` we distinguish between end-of-stream and error
- // by looking if `errno` was updated.
+ while (true) {
+ // In case `readdir()` returns `NULL` we distinguish between end-of-stream
+ // and error by looking if `errno` was updated.
errno = 0;
// In glibc 2.24+, readdir_r is deprecated.
// According to the man page for readdir:
// "readdir(3) is not required to be thread-safe. However, in modern
// implementations (including the glibc implementation), concurrent calls to
- // readdir(3) that specify different directory streams are thread-safe.
- // Therefore, the use of readdir_r() is generally unnecessary in multithreaded
- // programs. In cases where multiple threads must read from the same directory
- // stream, using readdir(3) with external synchronization is still preferable
- // to the use of readdir_r(), for the reasons given in the points above."
+ // readdir(3) that specify different directory streams are thread-safe."
dirent* entry = readdir(dir_pointer);
if (entry == NULL) {
// Failed to read next directory entry.
if (errno != 0) {
- break;
+ break;
}
// End of directory.
return (NO_RETRY_EXPECTED(closedir(dir_pointer)) == 0) &&
@@ -357,19 +345,14 @@
return DOES_NOT_EXIST;
}
} else {
- if ((errno == EACCES) ||
- (errno == EBADF) ||
- (errno == EFAULT) ||
- (errno == ENOMEM) ||
- (errno == EOVERFLOW)) {
+ if ((errno == EACCES) || (errno == EBADF) || (errno == EFAULT) ||
+ (errno == ENOMEM) || (errno == EOVERFLOW)) {
// Search permissions denied for one of the directories in the
// path or a low level error occured. We do not know if the
// directory exists.
return UNKNOWN;
}
- ASSERT((errno == ELOOP) ||
- (errno == ENAMETOOLONG) ||
- (errno == ENOENT) ||
+ ASSERT((errno == ELOOP) || (errno == ENAMETOOLONG) || (errno == ENOENT) ||
(errno == ENOTDIR));
return DOES_NOT_EXIST;
}
diff --git a/runtime/bin/directory_macos.cc b/runtime/bin/directory_macos.cc
index 5c0f5a6..18c254c 100644
--- a/runtime/bin/directory_macos.cc
+++ b/runtime/bin/directory_macos.cc
@@ -7,12 +7,12 @@
#include "bin/directory.h"
-#include <dirent.h> // NOLINT
-#include <errno.h> // NOLINT
-#include <string.h> // NOLINT
+#include <dirent.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <string.h> // NOLINT
#include <sys/param.h> // NOLINT
-#include <sys/stat.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <sys/stat.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/dartutils.h"
#include "bin/file.h"
@@ -56,13 +56,9 @@
bool PathBuffer::Add(const char* name) {
char* data = AsString();
- int written = snprintf(data + length_,
- PATH_MAX - length_,
- "%s",
- name);
+ int written = snprintf(data + length_, PATH_MAX - length_, "%s", name);
data[PATH_MAX] = '\0';
- if ((written <= PATH_MAX - length_) &&
- (written >= 0) &&
+ if ((written <= PATH_MAX - length_) && (written >= 0) &&
(static_cast<size_t>(written) == strlen(name))) {
length_ += written;
return true;
@@ -119,8 +115,8 @@
int status = 0;
dirent entry;
dirent* result;
- status = NO_RETRY_EXPECTED(readdir_r(
- reinterpret_cast<DIR*>(lister_), &entry, &result));
+ status = NO_RETRY_EXPECTED(
+ readdir_r(reinterpret_cast<DIR*>(lister_), &entry, &result));
if ((status == 0) && (result != NULL)) {
if (!listing->path_buffer().Add(entry.d_name)) {
done_ = true;
@@ -139,8 +135,8 @@
if (!listing->follow_links()) {
return kListLink;
}
- // Else fall through to next case.
- // Fall through.
+ // Else fall through to next case.
+ // Fall through.
case DT_UNKNOWN: {
// On some file systems the entry type is not determined by
// readdir_r. For those and for links we use stat to determine
@@ -155,9 +151,7 @@
}
if (listing->follow_links() && S_ISLNK(entry_info.st_mode)) {
// Check to see if we are in a loop created by a symbolic link.
- LinkList current_link = { entry_info.st_dev,
- entry_info.st_ino,
- link_ };
+ LinkList current_link = {entry_info.st_dev, entry_info.st_ino, link_};
LinkList* previous = link_;
while (previous != NULL) {
if ((previous->dev == current_link.dev) &&
@@ -234,14 +228,12 @@
static bool DeleteRecursively(PathBuffer* path);
-static bool DeleteFile(char* file_name,
- PathBuffer* path) {
+static bool DeleteFile(char* file_name, PathBuffer* path) {
return path->Add(file_name) && (unlink(path->AsString()) == 0);
}
-static bool DeleteDir(char* dir_name,
- PathBuffer* path) {
+static bool DeleteDir(char* dir_name, PathBuffer* path) {
if ((strcmp(dir_name, ".") == 0) || (strcmp(dir_name, "..") == 0)) {
return true;
}
@@ -344,19 +336,14 @@
return DOES_NOT_EXIST;
}
} else {
- if ((errno == EACCES) ||
- (errno == EBADF) ||
- (errno == EFAULT) ||
- (errno == ENOMEM) ||
- (errno == EOVERFLOW)) {
+ if ((errno == EACCES) || (errno == EBADF) || (errno == EFAULT) ||
+ (errno == ENOMEM) || (errno == EOVERFLOW)) {
// Search permissions denied for one of the directories in the
// path or a low level error occured. We do not know if the
// directory exists.
return UNKNOWN;
}
- ASSERT((errno == ELOOP) ||
- (errno == ENAMETOOLONG) ||
- (errno == ENOENT) ||
+ ASSERT((errno == ELOOP) || (errno == ENAMETOOLONG) || (errno == ENOENT) ||
(errno == ENOTDIR));
return DOES_NOT_EXIST;
}
diff --git a/runtime/bin/directory_test.cc b/runtime/bin/directory_test.cc
index 35c0d22..da4a084 100644
--- a/runtime/bin/directory_test.cc
+++ b/runtime/bin/directory_test.cc
@@ -131,8 +131,8 @@
snprintf(NULL, 0, "%s/%snewname", system_temp, kTempDirName);
ASSERT(new_name_len > 0);
char* new_name = new char[new_name_len + 1];
- snprintf(new_name, new_name_len + 1, "%s/%snewname",
- system_temp, kTempDirName);
+ snprintf(new_name, new_name_len + 1, "%s/%snewname", system_temp,
+ kTempDirName);
EXPECT(dart::bin::Directory::Rename(name, new_name));
diff --git a/runtime/bin/directory_unsupported.cc b/runtime/bin/directory_unsupported.cc
index c4398bb..d3a5152 100644
--- a/runtime/bin/directory_unsupported.cc
+++ b/runtime/bin/directory_unsupported.cc
@@ -13,70 +13,70 @@
void FUNCTION_NAME(Directory_Current)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Directory is not supported on this platform"));
+ "Directory is not supported on this platform"));
}
void FUNCTION_NAME(Directory_SetCurrent)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Directory is not supported on this platform"));
+ "Directory is not supported on this platform"));
}
void FUNCTION_NAME(Directory_Exists)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Directory is not supported on this platform"));
+ "Directory is not supported on this platform"));
}
void FUNCTION_NAME(Directory_Create)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Directory is not supported on this platform"));
+ "Directory is not supported on this platform"));
}
void FUNCTION_NAME(Directory_SystemTemp)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Directory is not supported on this platform"));
+ "Directory is not supported on this platform"));
}
void FUNCTION_NAME(Directory_CreateTemp)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Directory is not supported on this platform"));
+ "Directory is not supported on this platform"));
}
void FUNCTION_NAME(Directory_Delete)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Directory is not supported on this platform"));
+ "Directory is not supported on this platform"));
}
void FUNCTION_NAME(Directory_Rename)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Directory is not supported on this platform"));
+ "Directory is not supported on this platform"));
}
void FUNCTION_NAME(Directory_FillWithDirectoryListing)(
Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Directory is not supported on this platform"));
+ "Directory is not supported on this platform"));
}
void FUNCTION_NAME(Directory_GetAsyncDirectoryListerPointer)(
Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Directory is not supported on this platform"));
+ "Directory is not supported on this platform"));
}
void FUNCTION_NAME(Directory_SetAsyncDirectoryListerPointer)(
Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Directory is not supported on this platform"));
+ "Directory is not supported on this platform"));
}
} // namespace bin
diff --git a/runtime/bin/directory_win.cc b/runtime/bin/directory_win.cc
index 4ebf512..e9a5be9 100644
--- a/runtime/bin/directory_win.cc
+++ b/runtime/bin/directory_win.cc
@@ -10,7 +10,7 @@
#include "bin/utils.h"
#include "bin/utils_win.h"
-#include <errno.h> // NOLINT
+#include <errno.h> // NOLINT
#include <sys/stat.h> // NOLINT
#include "bin/dartutils.h"
@@ -57,13 +57,10 @@
bool PathBuffer::AddW(const wchar_t* name) {
wchar_t* data = AsStringW();
- int written = _snwprintf(data + length_,
- MAX_LONG_PATH - length_,
- L"%s",
- name);
+ int written =
+ _snwprintf(data + length_, MAX_LONG_PATH - length_, L"%s", name);
data[MAX_LONG_PATH] = L'\0';
- if ((written <= MAX_LONG_PATH - length_) &&
- (written >= 0) &&
+ if ((written <= MAX_LONG_PATH - length_) && (written >= 0) &&
(static_cast<size_t>(written) == wcsnlen(name, MAX_LONG_PATH + 1))) {
length_ += written;
return true;
@@ -84,13 +81,8 @@
// points to an invalid target.
static bool IsBrokenLink(const wchar_t* link_name) {
HANDLE handle = CreateFileW(
- link_name,
- 0,
- FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
- NULL,
- OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS,
- NULL);
+ link_name, 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (handle == INVALID_HANDLE_VALUE) {
return true;
} else {
@@ -124,14 +116,10 @@
if (!listing->follow_links()) {
return kListLink;
}
- HANDLE handle = CreateFileW(
- listing->path_buffer().AsStringW(),
- 0,
- FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
- NULL,
- OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS,
- NULL);
+ HANDLE handle =
+ CreateFileW(listing->path_buffer().AsStringW(), 0,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (handle == INVALID_HANDLE_VALUE) {
// Report as (broken) link.
return kListLink;
@@ -199,8 +187,8 @@
path_length_ = listing->path_buffer().length() - 1;
- HANDLE find_handle = FindFirstFileW(listing->path_buffer().AsStringW(),
- &find_file_data);
+ HANDLE find_handle =
+ FindFirstFileW(listing->path_buffer().AsStringW(), &find_file_data);
if (find_handle == INVALID_HANDLE_VALUE) {
done_ = true;
@@ -285,8 +273,7 @@
static bool DeleteDir(wchar_t* dir_name, PathBuffer* path) {
- if ((wcscmp(dir_name, L".") == 0) ||
- (wcscmp(dir_name, L"..") == 0)) {
+ if ((wcscmp(dir_name, L".") == 0) || (wcscmp(dir_name, L"..") == 0)) {
return true;
}
return path->AddW(dir_name) && DeleteRecursively(path);
@@ -389,8 +376,8 @@
}
wchar_t* current = new wchar_t[length + 1];
GetCurrentDirectoryW(length + 1, current);
- int utf8_len = WideCharToMultiByte(
- CP_UTF8, 0, current, -1, NULL, 0, NULL, NULL);
+ int utf8_len =
+ WideCharToMultiByte(CP_UTF8, 0, current, -1, NULL, 0, NULL, NULL);
char* result = reinterpret_cast<char*>(malloc(utf8_len));
WideCharToMultiByte(CP_UTF8, 0, current, -1, result, utf8_len, NULL, NULL);
delete[] current;
@@ -422,8 +409,7 @@
Utf8ToWideScope system_name(dir_name);
int create_status = CreateDirectoryW(system_name.wide(), NULL);
// If the directory already existed, treat it as a success.
- if ((create_status == 0) &&
- (GetLastError() == ERROR_ALREADY_EXISTS) &&
+ if ((create_status == 0) && (GetLastError() == ERROR_ALREADY_EXISTS) &&
(ExistsHelper(system_name.wide()) == EXISTS)) {
return true;
}
diff --git a/runtime/bin/eventhandler.cc b/runtime/bin/eventhandler.cc
index 8ce45b2..60c13a5 100644
--- a/runtime/bin/eventhandler.cc
+++ b/runtime/bin/eventhandler.cc
@@ -59,7 +59,7 @@
static EventHandler* event_handler = NULL;
-static Monitor *shutdown_monitor = NULL;
+static Monitor* shutdown_monitor = NULL;
void EventHandler::Start() {
diff --git a/runtime/bin/eventhandler.h b/runtime/bin/eventhandler.h
index 849c3ed..50852cd 100644
--- a/runtime/bin/eventhandler.h
+++ b/runtime/bin/eventhandler.h
@@ -33,26 +33,28 @@
kPipe = 17,
};
-#define COMMAND_MASK ((1 << kCloseCommand) | \
- (1 << kShutdownReadCommand) | \
- (1 << kShutdownWriteCommand) | \
- (1 << kReturnTokenCommand) | \
+// clang-format off
+#define COMMAND_MASK ((1 << kCloseCommand) | \
+ (1 << kShutdownReadCommand) | \
+ (1 << kShutdownWriteCommand) | \
+ (1 << kReturnTokenCommand) | \
(1 << kSetEventMaskCommand))
-#define EVENT_MASK ((1 << kInEvent) | \
- (1 << kOutEvent) | \
- (1 << kErrorEvent) | \
- (1 << kCloseEvent) | \
+#define EVENT_MASK ((1 << kInEvent) | \
+ (1 << kOutEvent) | \
+ (1 << kErrorEvent) | \
+ (1 << kCloseEvent) | \
(1 << kDestroyedEvent))
-#define IS_COMMAND(data, command_bit) \
+#define IS_COMMAND(data, command_bit) \
((data & COMMAND_MASK) == (1 << command_bit)) // NOLINT
-#define IS_EVENT(data, event_bit) \
+#define IS_EVENT(data, event_bit) \
((data & EVENT_MASK) == (1 << event_bit)) // NOLINT
-#define IS_IO_EVENT(data) \
- ((data & (1 << kInEvent | 1 << kOutEvent | 1 << kCloseEvent)) != 0 && \
+#define IS_IO_EVENT(data) \
+ ((data & (1 << kInEvent | 1 << kOutEvent | 1 << kCloseEvent)) != 0 && \
(data & ~(1 << kInEvent | 1 << kOutEvent | 1 << kCloseEvent)) == 0)
-#define IS_LISTENING_SOCKET(data) \
+#define IS_LISTENING_SOCKET(data) \
((data & (1 << kListeningSocket)) != 0) // NOLINT
#define TOKEN_COUNT(data) (data & ((1 << kCloseCommand) - 1))
+// clang-format on
class TimeoutQueue {
private:
@@ -70,9 +72,7 @@
}
Timeout* next() const { return next_; }
- void set_next(Timeout* next) {
- next_ = next;
- }
+ void set_next(Timeout* next) { next_ = next; }
private:
Dart_Port port_;
@@ -84,7 +84,8 @@
TimeoutQueue() : next_timeout_(NULL), timeouts_(NULL) {}
~TimeoutQueue() {
- while (HasTimeout()) RemoveCurrent();
+ while (HasTimeout())
+ RemoveCurrent();
}
bool HasTimeout() const { return next_timeout_ != NULL; }
@@ -99,9 +100,7 @@
return next_timeout_->port();
}
- void RemoveCurrent() {
- UpdateTimeout(CurrentPort(), -1);
- }
+ void RemoveCurrent() { UpdateTimeout(CurrentPort(), -1); }
void UpdateTimeout(Dart_Port port, int64_t timeout);
@@ -127,12 +126,12 @@
static const int kShutdownId = -2;
-template<typename T>
+template <typename T>
class CircularLinkedList {
public:
CircularLinkedList() : head_(NULL) {}
- typedef void (*ClearFun) (void* value);
+ typedef void (*ClearFun)(void* value);
// Returns true if the list was empty.
bool Add(T t) {
@@ -180,11 +179,11 @@
return;
}
} else {
- Entry *current = head_;
+ Entry* current = head_;
do {
if (current->t == item) {
- Entry *next = current->next_;
- Entry *prev = current->prev_;
+ Entry* next = current->next_;
+ Entry* prev = current->prev_;
prev->next_ = next;
next->prev_ = prev;
@@ -208,9 +207,7 @@
T head() const { return head_->t; }
- bool HasHead() const {
- return head_ != NULL;
- }
+ bool HasHead() const { return head_ != NULL; }
void Rotate() {
if (head_ != NULL) {
@@ -235,9 +232,7 @@
class DescriptorInfoBase {
public:
- explicit DescriptorInfoBase(intptr_t fd) : fd_(fd) {
- ASSERT(fd_ != -1);
- }
+ explicit DescriptorInfoBase(intptr_t fd) : fd_(fd) { ASSERT(fd_ != -1); }
virtual ~DescriptorInfoBase() {}
@@ -287,17 +282,20 @@
// windows) which is connected to a single Dart_Port.
//
// Subclasses of this class can be e.g. connected tcp sockets.
-template<typename DI>
+template <typename DI>
class DescriptorInfoSingleMixin : public DI {
private:
static const int kTokenCount = 16;
public:
DescriptorInfoSingleMixin(intptr_t fd, bool disable_tokens)
- : DI(fd), port_(0), tokens_(kTokenCount), mask_(0),
+ : DI(fd),
+ port_(0),
+ tokens_(kTokenCount),
+ mask_(0),
disable_tokens_(disable_tokens) {}
- virtual ~DescriptorInfoSingleMixin() { }
+ virtual ~DescriptorInfoSingleMixin() {}
virtual bool IsListeningSocket() const { return false; }
@@ -332,8 +330,7 @@
virtual void NotifyAllDartPorts(uintptr_t events) {
// Unexpected close, asynchronous destroy or error events are the only
// ones we broadcast to all listeners.
- ASSERT(IS_EVENT(events, kCloseEvent) ||
- IS_EVENT(events, kErrorEvent) ||
+ ASSERT(IS_EVENT(events, kCloseEvent) || IS_EVENT(events, kErrorEvent) ||
IS_EVENT(events, kDestroyedEvent));
if (port_ != 0) {
@@ -359,9 +356,7 @@
return mask_;
}
- virtual void Close() {
- DI::Close();
- }
+ virtual void Close() { DI::Close(); }
private:
Dart_Port port_;
@@ -378,14 +373,14 @@
//
// Subclasses of this class can be e.g. a listening socket which multiple
// isolates are listening on.
-template<typename DI>
+template <typename DI>
class DescriptorInfoMultipleMixin : public DI {
private:
static const int kTokenCount = 4;
static bool SamePortValue(void* key1, void* key2) {
return reinterpret_cast<Dart_Port>(key1) ==
- reinterpret_cast<Dart_Port>(key2);
+ reinterpret_cast<Dart_Port>(key2);
}
static uint32_t GetHashmapHashFromPort(Dart_Port port) {
@@ -415,12 +410,11 @@
public:
DescriptorInfoMultipleMixin(intptr_t fd, bool disable_tokens)
- : DI(fd), tokens_map_(&SamePortValue, kTokenCount),
+ : DI(fd),
+ tokens_map_(&SamePortValue, kTokenCount),
disable_tokens_(disable_tokens) {}
- virtual ~DescriptorInfoMultipleMixin() {
- RemoveAllPorts();
- }
+ virtual ~DescriptorInfoMultipleMixin() { RemoveAllPorts(); }
virtual bool IsListeningSocket() const { return true; }
@@ -466,8 +460,7 @@
} while (current != root);
}
- for (HashMap::Entry *entry = tokens_map_.Start();
- entry != NULL;
+ for (HashMap::Entry* entry = tokens_map_.Start(); entry != NULL;
entry = tokens_map_.Next(entry)) {
PortEntry* pentry = reinterpret_cast<PortEntry*>(entry->value);
if (pentry->IsReady()) {
@@ -487,8 +480,8 @@
if (pentry->IsReady()) {
active_readers_.Remove(pentry);
}
- tokens_map_.Remove(
- GetHashmapKeyFromPort(port), GetHashmapHashFromPort(port));
+ tokens_map_.Remove(GetHashmapKeyFromPort(port),
+ GetHashmapHashFromPort(port));
delete pentry;
} else {
// NOTE: This is a listening socket which has been immediately closed.
@@ -504,8 +497,7 @@
}
virtual void RemoveAllPorts() {
- for (HashMap::Entry *entry = tokens_map_.Start();
- entry != NULL;
+ for (HashMap::Entry* entry = tokens_map_.Start(); entry != NULL;
entry = tokens_map_.Next(entry)) {
PortEntry* pentry = reinterpret_cast<PortEntry*>(entry->value);
entry->value = NULL;
@@ -543,12 +535,10 @@
virtual void NotifyAllDartPorts(uintptr_t events) {
// Unexpected close, asynchronous destroy or error events are the only
// ones we broadcast to all listeners.
- ASSERT(IS_EVENT(events, kCloseEvent) ||
- IS_EVENT(events, kErrorEvent) ||
+ ASSERT(IS_EVENT(events, kCloseEvent) || IS_EVENT(events, kErrorEvent) ||
IS_EVENT(events, kDestroyedEvent));
- for (HashMap::Entry *entry = tokens_map_.Start();
- entry != NULL;
+ for (HashMap::Entry* entry = tokens_map_.Start(); entry != NULL;
entry = tokens_map_.Next(entry)) {
PortEntry* pentry = reinterpret_cast<PortEntry*>(entry->value);
DartUtils::PostInt32(pentry->dart_port, events);
@@ -589,9 +579,7 @@
return 0;
}
- virtual void Close() {
- DI::Close();
- }
+ virtual void Close() { DI::Close(); }
private:
static void DeletePortEntry(void* data) {
@@ -602,7 +590,7 @@
// The [Dart_Port]s which are not paused (i.e. are interested in read events,
// i.e. `mask == (1 << kInEvent)`) and we have enough tokens to communicate
// with them.
- CircularLinkedList<PortEntry *> active_readers_;
+ CircularLinkedList<PortEntry*> active_readers_;
// A convenience mapping:
// Dart_Port -> struct PortEntry { dart_port, mask, token_count }
diff --git a/runtime/bin/eventhandler_android.cc b/runtime/bin/eventhandler_android.cc
index c298a04..c3f6836 100644
--- a/runtime/bin/eventhandler_android.cc
+++ b/runtime/bin/eventhandler_android.cc
@@ -10,14 +10,14 @@
#include "bin/eventhandler.h"
#include "bin/eventhandler_android.h"
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
-#include <pthread.h> // NOLINT
-#include <stdio.h> // NOLINT
-#include <string.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <pthread.h> // NOLINT
+#include <stdio.h> // NOLINT
+#include <string.h> // NOLINT
#include <sys/epoll.h> // NOLINT
-#include <sys/stat.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <sys/stat.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/dartutils.h"
#include "bin/fdutils.h"
@@ -53,12 +53,8 @@
// Unregister the file descriptor for a DescriptorInfo structure with
// epoll.
-static void RemoveFromEpollInstance(intptr_t epoll_fd_,
- DescriptorInfo* di) {
- VOID_NO_RETRY_EXPECTED(epoll_ctl(epoll_fd_,
- EPOLL_CTL_DEL,
- di->fd(),
- NULL));
+static void RemoveFromEpollInstance(intptr_t epoll_fd_, DescriptorInfo* di) {
+ VOID_NO_RETRY_EXPECTED(epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, di->fd(), NULL));
}
@@ -69,10 +65,8 @@
event.events |= EPOLLET;
}
event.data.ptr = di;
- int status = NO_RETRY_EXPECTED(epoll_ctl(epoll_fd_,
- EPOLL_CTL_ADD,
- di->fd(),
- &event));
+ int status =
+ NO_RETRY_EXPECTED(epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, di->fd(), &event));
if (status == -1) {
// TODO(dart:io): Verify that the dart end is handling this correctly.
@@ -108,10 +102,8 @@
struct epoll_event event;
event.events = EPOLLIN;
event.data.ptr = NULL;
- int status = NO_RETRY_EXPECTED(epoll_ctl(epoll_fd_,
- EPOLL_CTL_ADD,
- interrupt_fds_[0],
- &event));
+ int status = NO_RETRY_EXPECTED(
+ epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, interrupt_fds_[0], &event));
if (status == -1) {
FATAL("Failed adding interrupt fd to epoll instance");
}
@@ -134,7 +126,7 @@
void EventHandlerImplementation::UpdateEpollInstance(intptr_t old_mask,
- DescriptorInfo *di) {
+ DescriptorInfo* di) {
intptr_t new_mask = di->Mask();
if ((old_mask != 0) && (new_mask == 0)) {
RemoveFromEpollInstance(epoll_fd_, di);
@@ -149,13 +141,13 @@
DescriptorInfo* EventHandlerImplementation::GetDescriptorInfo(
- intptr_t fd, bool is_listening) {
+ intptr_t fd,
+ bool is_listening) {
ASSERT(fd >= 0);
- HashMap::Entry* entry = socket_map_.Lookup(
- GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd), true);
+ HashMap::Entry* entry = socket_map_.Lookup(GetHashmapKeyFromFd(fd),
+ GetHashmapHashFromFd(fd), true);
ASSERT(entry != NULL);
- DescriptorInfo* di =
- reinterpret_cast<DescriptorInfo*>(entry->value);
+ DescriptorInfo* di = reinterpret_cast<DescriptorInfo*>(entry->value);
if (di == NULL) {
// If there is no data in the hash map for this file descriptor a
// new DescriptorInfo for the file descriptor is inserted.
@@ -206,8 +198,8 @@
} else {
ASSERT((msg[i].data & COMMAND_MASK) != 0);
- DescriptorInfo* di = GetDescriptorInfo(
- msg[i].id, IS_LISTENING_SOCKET(msg[i].data));
+ DescriptorInfo* di =
+ GetDescriptorInfo(msg[i].id, IS_LISTENING_SOCKET(msg[i].data));
if (IS_COMMAND(msg[i].data, kShutdownReadCommand)) {
ASSERT(!di->IsListeningSocket());
// Close the socket for reading.
@@ -230,7 +222,7 @@
// We only close the socket file descriptor from the operating
// system if there are no other dart socket objects which
// are listening on the same (address, port) combination.
- ListeningSocketRegistry *registry =
+ ListeningSocketRegistry* registry =
ListeningSocketRegistry::Instance();
MutexLocker locker(registry->mutex());
@@ -244,8 +236,7 @@
}
} else {
ASSERT(new_mask == 0);
- socket_map_.Remove(
- GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd));
+ socket_map_.Remove(GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd));
di->Close();
delete di;
}
@@ -293,8 +284,8 @@
if ((events & EPOLLRDHUP) != 0) {
Log::Print("EPOLLRDHUP ");
}
- int all_events = EPOLLIN | EPOLLPRI | EPOLLOUT |
- EPOLLERR | EPOLLHUP | EPOLLRDHUP;
+ int all_events =
+ EPOLLIN | EPOLLPRI | EPOLLOUT | EPOLLERR | EPOLLHUP | EPOLLRDHUP;
if ((events & ~all_events) != 0) {
Log::Print("(and %08x) ", events & ~all_events);
}
@@ -359,8 +350,8 @@
if (!timeout_queue_.HasTimeout()) {
return kInfinityTimeout;
}
- int64_t millis = timeout_queue_.CurrentTimeout() -
- TimerUtils::GetCurrentMonotonicMillis();
+ int64_t millis =
+ timeout_queue_.CurrentTimeout() - TimerUtils::GetCurrentMonotonicMillis();
return (millis < 0) ? 0 : millis;
}
@@ -368,7 +359,7 @@
void EventHandlerImplementation::HandleTimeout() {
if (timeout_queue_.HasTimeout()) {
int64_t millis = timeout_queue_.CurrentTimeout() -
- TimerUtils::GetCurrentMonotonicMillis();
+ TimerUtils::GetCurrentMonotonicMillis();
if (millis <= 0) {
DartUtils::PostNull(timeout_queue_.CurrentPort());
timeout_queue_.RemoveCurrent();
diff --git a/runtime/bin/eventhandler_android.h b/runtime/bin/eventhandler_android.h
index c2f72bc..156ba4f 100644
--- a/runtime/bin/eventhandler_android.h
+++ b/runtime/bin/eventhandler_android.h
@@ -23,9 +23,9 @@
class DescriptorInfo : public DescriptorInfoBase {
public:
- explicit DescriptorInfo(intptr_t fd) : DescriptorInfoBase(fd) { }
+ explicit DescriptorInfo(intptr_t fd) : DescriptorInfoBase(fd) {}
- virtual ~DescriptorInfo() { }
+ virtual ~DescriptorInfo() {}
intptr_t GetPollEvents();
@@ -39,8 +39,7 @@
};
-class DescriptorInfoSingle
- : public DescriptorInfoSingleMixin<DescriptorInfo> {
+class DescriptorInfoSingle : public DescriptorInfoSingleMixin<DescriptorInfo> {
public:
explicit DescriptorInfoSingle(intptr_t fd)
: DescriptorInfoSingleMixin(fd, false) {}
@@ -68,7 +67,7 @@
EventHandlerImplementation();
~EventHandlerImplementation();
- void UpdateEpollInstance(intptr_t old_mask, DescriptorInfo *di);
+ void UpdateEpollInstance(intptr_t old_mask, DescriptorInfo* di);
// Gets the socket data structure for a given file
// descriptor. Creates a new one if one is not found.
diff --git a/runtime/bin/eventhandler_fuchsia.cc b/runtime/bin/eventhandler_fuchsia.cc
index 3e7096b..2d0ebe3 100644
--- a/runtime/bin/eventhandler_fuchsia.cc
+++ b/runtime/bin/eventhandler_fuchsia.cc
@@ -29,15 +29,14 @@
namespace bin {
MagentaWaitManyInfo::MagentaWaitManyInfo()
- : capacity_(kInitialCapacity),
- size_(0) {
+ : capacity_(kInitialCapacity), size_(0) {
descriptor_infos_ = static_cast<DescriptorInfo**>(
malloc(kInitialCapacity * sizeof(*descriptor_infos_)));
if (descriptor_infos_ == NULL) {
FATAL("Failed to allocate descriptor_infos array");
}
- items_ = static_cast<mx_wait_item_t*>(
- malloc(kInitialCapacity * sizeof(*items_)));
+ items_ =
+ static_cast<mx_wait_item_t*>(malloc(kInitialCapacity * sizeof(*items_)));
if (items_ == NULL) {
FATAL("Failed to allocate items array");
}
@@ -110,21 +109,20 @@
FATAL("Failed to grow items array");
}
capacity_ = new_capacity;
- LOG_INFO("GrowArraysIfNeeded(%ld), capacity = %ld\n",
- desired_size, capacity_);
+ LOG_INFO("GrowArraysIfNeeded(%ld), capacity = %ld\n", desired_size,
+ capacity_);
}
EventHandlerImplementation::EventHandlerImplementation() {
- mx_status_t status = mx_channel_create(0, &interrupt_handles_[0],
- &interrupt_handles_[1]);
+ mx_status_t status =
+ mx_channel_create(0, &interrupt_handles_[0], &interrupt_handles_[1]);
if (status != NO_ERROR) {
FATAL1("mx_channel_create failed: %s\n", mx_status_get_string(status));
}
shutdown_ = false;
info_.AddHandle(interrupt_handles_[0],
- MX_SIGNAL_READABLE | MX_SIGNAL_PEER_CLOSED,
- NULL);
+ MX_SIGNAL_READABLE | MX_SIGNAL_PEER_CLOSED, NULL);
LOG_INFO("EventHandlerImplementation initialized\n");
}
@@ -151,7 +149,7 @@
msg.data = data;
mx_status_t status =
- mx_channel_write(interrupt_handles_[1], 0, &msg, sizeof(msg), NULL, 0);
+ mx_channel_write(interrupt_handles_[1], 0, &msg, sizeof(msg), NULL, 0);
if (status != NO_ERROR) {
FATAL1("mx_channel_write failed: %s\n", mx_status_get_string(status));
}
@@ -165,8 +163,8 @@
uint32_t bytes = kInterruptMessageSize;
mx_status_t status;
while (true) {
- status = mx_channel_read(
- interrupt_handles_[0], 0, &msg, bytes, &bytes, NULL, 0, NULL);
+ status = mx_channel_read(interrupt_handles_[0], 0, &msg, bytes, &bytes,
+ NULL, 0, NULL);
if (status != NO_ERROR) {
break;
}
@@ -222,8 +220,8 @@
if (!timeout_queue_.HasTimeout()) {
return kInfinityTimeout;
}
- int64_t millis = timeout_queue_.CurrentTimeout() -
- TimerUtils::GetCurrentMonotonicMillis();
+ int64_t millis =
+ timeout_queue_.CurrentTimeout() - TimerUtils::GetCurrentMonotonicMillis();
return (millis < 0) ? 0 : millis;
}
@@ -231,7 +229,7 @@
void EventHandlerImplementation::HandleTimeout() {
if (timeout_queue_.HasTimeout()) {
int64_t millis = timeout_queue_.CurrentTimeout() -
- TimerUtils::GetCurrentMonotonicMillis();
+ TimerUtils::GetCurrentMonotonicMillis();
if (millis <= 0) {
DartUtils::PostNull(timeout_queue_.CurrentPort());
timeout_queue_.RemoveCurrent();
@@ -251,12 +249,10 @@
mx_time_t timeout =
millis * kMicrosecondsPerMillisecond * kNanosecondsPerMicrosecond;
const MagentaWaitManyInfo& info = handler_impl->info();
- LOG_INFO("mx_handle_wait_many(%p, %ld, %lld)\n",
- info.items(), info.size(), timeout);
- mx_status_t status = mx_handle_wait_many(
- info.items(),
- info.size(),
- timeout);
+ LOG_INFO("mx_handle_wait_many(%p, %ld, %lld)\n", info.items(), info.size(),
+ timeout);
+ mx_status_t status =
+ mx_handle_wait_many(info.items(), info.size(), timeout);
if ((status != NO_ERROR) && (status != ERR_TIMED_OUT)) {
FATAL1("mx_handle_wait_many failed: %s\n", mx_status_get_string(status));
} else {
diff --git a/runtime/bin/eventhandler_fuchsia.h b/runtime/bin/eventhandler_fuchsia.h
index a15b4e1..acd4793 100644
--- a/runtime/bin/eventhandler_fuchsia.h
+++ b/runtime/bin/eventhandler_fuchsia.h
@@ -6,7 +6,7 @@
#define RUNTIME_BIN_EVENTHANDLER_FUCHSIA_H_
#if !defined(RUNTIME_BIN_EVENTHANDLER_H_)
-#error Do not include eventhandler_fuchsia.h directly; use eventhandler.h instead.
+#error Do not include eventhandler_fuchsia.h directly; use eventhandler.h.
#endif
#include <errno.h>
@@ -19,9 +19,9 @@
class DescriptorInfo : public DescriptorInfoBase {
public:
- explicit DescriptorInfo(intptr_t fd) : DescriptorInfoBase(fd) { }
+ explicit DescriptorInfo(intptr_t fd) : DescriptorInfoBase(fd) {}
- virtual ~DescriptorInfo() { }
+ virtual ~DescriptorInfo() {}
virtual void Close() {
VOID_TEMP_FAILURE_RETRY(close(fd_));
@@ -32,8 +32,7 @@
DISALLOW_COPY_AND_ASSIGN(DescriptorInfo);
};
-class DescriptorInfoSingle
- : public DescriptorInfoSingleMixin<DescriptorInfo> {
+class DescriptorInfoSingle : public DescriptorInfoSingleMixin<DescriptorInfo> {
public:
explicit DescriptorInfoSingle(intptr_t fd)
: DescriptorInfoSingleMixin(fd, false) {}
diff --git a/runtime/bin/eventhandler_linux.cc b/runtime/bin/eventhandler_linux.cc
index bd61e80..fd410fe 100644
--- a/runtime/bin/eventhandler_linux.cc
+++ b/runtime/bin/eventhandler_linux.cc
@@ -10,15 +10,15 @@
#include "bin/eventhandler.h"
#include "bin/eventhandler_linux.h"
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
-#include <pthread.h> // NOLINT
-#include <stdio.h> // NOLINT
-#include <string.h> // NOLINT
-#include <sys/epoll.h> // NOLINT
-#include <sys/stat.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <pthread.h> // NOLINT
+#include <stdio.h> // NOLINT
+#include <string.h> // NOLINT
+#include <sys/epoll.h> // NOLINT
+#include <sys/stat.h> // NOLINT
#include <sys/timerfd.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/dartutils.h"
#include "bin/fdutils.h"
@@ -47,12 +47,8 @@
// Unregister the file descriptor for a DescriptorInfo structure with
// epoll.
-static void RemoveFromEpollInstance(intptr_t epoll_fd_,
- DescriptorInfo* di) {
- VOID_NO_RETRY_EXPECTED(epoll_ctl(epoll_fd_,
- EPOLL_CTL_DEL,
- di->fd(),
- NULL));
+static void RemoveFromEpollInstance(intptr_t epoll_fd_, DescriptorInfo* di) {
+ VOID_NO_RETRY_EXPECTED(epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, di->fd(), NULL));
}
@@ -63,10 +59,8 @@
event.events |= EPOLLET;
}
event.data.ptr = di;
- int status = NO_RETRY_EXPECTED(epoll_ctl(epoll_fd_,
- EPOLL_CTL_ADD,
- di->fd(),
- &event));
+ int status =
+ NO_RETRY_EXPECTED(epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, di->fd(), &event));
if (status == -1) {
// TODO(dart:io): Verify that the dart end is handling this correctly.
@@ -102,10 +96,8 @@
struct epoll_event event;
event.events = EPOLLIN;
event.data.ptr = NULL;
- int status = NO_RETRY_EXPECTED(epoll_ctl(epoll_fd_,
- EPOLL_CTL_ADD,
- interrupt_fds_[0],
- &event));
+ int status = NO_RETRY_EXPECTED(
+ epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, interrupt_fds_[0], &event));
if (status == -1) {
FATAL("Failed adding interrupt fd to epoll instance");
}
@@ -116,13 +108,11 @@
// Register the timer_fd_ with the epoll instance.
event.events = EPOLLIN;
event.data.fd = timer_fd_;
- status = NO_RETRY_EXPECTED(epoll_ctl(epoll_fd_,
- EPOLL_CTL_ADD,
- timer_fd_,
- &event));
+ status =
+ NO_RETRY_EXPECTED(epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, timer_fd_, &event));
if (status == -1) {
- FATAL2(
- "Failed adding timerfd fd(%i) to epoll instance: %i", timer_fd_, errno);
+ FATAL2("Failed adding timerfd fd(%i) to epoll instance: %i", timer_fd_,
+ errno);
}
}
@@ -144,7 +134,7 @@
void EventHandlerImplementation::UpdateEpollInstance(intptr_t old_mask,
- DescriptorInfo *di) {
+ DescriptorInfo* di) {
intptr_t new_mask = di->Mask();
if ((old_mask != 0) && (new_mask == 0)) {
RemoveFromEpollInstance(epoll_fd_, di);
@@ -159,10 +149,11 @@
DescriptorInfo* EventHandlerImplementation::GetDescriptorInfo(
- intptr_t fd, bool is_listening) {
+ intptr_t fd,
+ bool is_listening) {
ASSERT(fd >= 0);
- HashMap::Entry* entry = socket_map_.Lookup(
- GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd), true);
+ HashMap::Entry* entry = socket_map_.Lookup(GetHashmapKeyFromFd(fd),
+ GetHashmapHashFromFd(fd), true);
ASSERT(entry != NULL);
DescriptorInfo* di = reinterpret_cast<DescriptorInfo*>(entry->value);
if (di == NULL) {
@@ -224,8 +215,8 @@
} else {
ASSERT((msg[i].data & COMMAND_MASK) != 0);
- DescriptorInfo* di = GetDescriptorInfo(
- msg[i].id, IS_LISTENING_SOCKET(msg[i].data));
+ DescriptorInfo* di =
+ GetDescriptorInfo(msg[i].id, IS_LISTENING_SOCKET(msg[i].data));
if (IS_COMMAND(msg[i].data, kShutdownReadCommand)) {
ASSERT(!di->IsListeningSocket());
// Close the socket for reading.
@@ -248,7 +239,7 @@
// We only close the socket file descriptor from the operating
// system if there are no other dart socket objects which
// are listening on the same (address, port) combination.
- ListeningSocketRegistry *registry =
+ ListeningSocketRegistry* registry =
ListeningSocketRegistry::Instance();
MutexLocker locker(registry->mutex());
@@ -262,8 +253,7 @@
}
} else {
ASSERT(new_mask == 0);
- socket_map_.Remove(
- GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd));
+ socket_map_.Remove(GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd));
di->Close();
delete di;
}
@@ -311,8 +301,8 @@
if ((events & EPOLLRDHUP) != 0) {
Log::Print("EPOLLRDHUP ");
}
- int all_events = EPOLLIN | EPOLLPRI | EPOLLOUT |
- EPOLLERR | EPOLLHUP | EPOLLRDHUP;
+ int all_events =
+ EPOLLIN | EPOLLPRI | EPOLLOUT | EPOLLERR | EPOLLHUP | EPOLLRDHUP;
if ((events & ~all_events) != 0) {
Log::Print("(and %08x) ", events & ~all_events);
}
diff --git a/runtime/bin/eventhandler_linux.h b/runtime/bin/eventhandler_linux.h
index ac46454..5386eb6 100644
--- a/runtime/bin/eventhandler_linux.h
+++ b/runtime/bin/eventhandler_linux.h
@@ -23,9 +23,9 @@
class DescriptorInfo : public DescriptorInfoBase {
public:
- explicit DescriptorInfo(intptr_t fd) : DescriptorInfoBase(fd) { }
+ explicit DescriptorInfo(intptr_t fd) : DescriptorInfoBase(fd) {}
- virtual ~DescriptorInfo() { }
+ virtual ~DescriptorInfo() {}
intptr_t GetPollEvents();
@@ -39,8 +39,7 @@
};
-class DescriptorInfoSingle
- : public DescriptorInfoSingleMixin<DescriptorInfo> {
+class DescriptorInfoSingle : public DescriptorInfoSingleMixin<DescriptorInfo> {
public:
explicit DescriptorInfoSingle(intptr_t fd)
: DescriptorInfoSingleMixin(fd, false) {}
@@ -68,7 +67,7 @@
EventHandlerImplementation();
~EventHandlerImplementation();
- void UpdateEpollInstance(intptr_t old_mask, DescriptorInfo *di);
+ void UpdateEpollInstance(intptr_t old_mask, DescriptorInfo* di);
// Gets the socket data structure for a given file
// descriptor. Creates a new one if one is not found.
diff --git a/runtime/bin/eventhandler_macos.cc b/runtime/bin/eventhandler_macos.cc
index b55ea8e..1e0fa94 100644
--- a/runtime/bin/eventhandler_macos.cc
+++ b/runtime/bin/eventhandler_macos.cc
@@ -10,13 +10,13 @@
#include "bin/eventhandler.h"
#include "bin/eventhandler_macos.h"
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
-#include <pthread.h> // NOLINT
-#include <stdio.h> // NOLINT
-#include <string.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <pthread.h> // NOLINT
+#include <stdio.h> // NOLINT
+#include <string.h> // NOLINT
#include <sys/event.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/dartutils.h"
#include "bin/fdutils.h"
@@ -72,24 +72,12 @@
// Register or unregister READ filter if needed.
if (di->HasReadEvent()) {
- EV_SET(events + changes,
- di->fd(),
- EVFILT_READ,
- flags,
- 0,
- 0,
- di);
+ EV_SET(events + changes, di->fd(), EVFILT_READ, flags, 0, 0, di);
++changes;
}
// Register or unregister WRITE filter if needed.
if (di->HasWriteEvent()) {
- EV_SET(events + changes,
- di->fd(),
- EVFILT_WRITE,
- flags,
- 0,
- 0,
- di);
+ EV_SET(events + changes, di->fd(), EVFILT_WRITE, flags, 0, 0, di);
++changes;
}
ASSERT(changes > 0);
@@ -156,7 +144,7 @@
void EventHandlerImplementation::UpdateKQueueInstance(intptr_t old_mask,
- DescriptorInfo *di) {
+ DescriptorInfo* di) {
intptr_t new_mask = di->Mask();
if (old_mask != 0 && new_mask == 0) {
RemoveFromKqueue(kqueue_fd_, di);
@@ -171,13 +159,13 @@
DescriptorInfo* EventHandlerImplementation::GetDescriptorInfo(
- intptr_t fd, bool is_listening) {
+ intptr_t fd,
+ bool is_listening) {
ASSERT(fd >= 0);
- HashMap::Entry* entry = socket_map_.Lookup(
- GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd), true);
+ HashMap::Entry* entry = socket_map_.Lookup(GetHashmapKeyFromFd(fd),
+ GetHashmapHashFromFd(fd), true);
ASSERT(entry != NULL);
- DescriptorInfo* di =
- reinterpret_cast<DescriptorInfo*>(entry->value);
+ DescriptorInfo* di = reinterpret_cast<DescriptorInfo*>(entry->value);
if (di == NULL) {
// If there is no data in the hash map for this file descriptor a
// new DescriptorInfo for the file descriptor is inserted.
@@ -227,8 +215,8 @@
} else {
ASSERT((msg[i].data & COMMAND_MASK) != 0);
- DescriptorInfo* di = GetDescriptorInfo(
- msg[i].id, IS_LISTENING_SOCKET(msg[i].data));
+ DescriptorInfo* di =
+ GetDescriptorInfo(msg[i].id, IS_LISTENING_SOCKET(msg[i].data));
if (IS_COMMAND(msg[i].data, kShutdownReadCommand)) {
ASSERT(!di->IsListeningSocket());
// Close the socket for reading.
@@ -251,7 +239,7 @@
// We only close the socket file descriptor from the operating
// system if there are no other dart socket objects which
// are listening on the same (address, port) combination.
- ListeningSocketRegistry *registry =
+ ListeningSocketRegistry* registry =
ListeningSocketRegistry::Instance();
MutexLocker locker(registry->mutex());
@@ -265,8 +253,7 @@
}
} else {
ASSERT(new_mask == 0);
- socket_map_.Remove(
- GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd));
+ socket_map_.Remove(GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd));
di->Close();
delete di;
}
@@ -379,8 +366,7 @@
}
-void EventHandlerImplementation::HandleEvents(struct kevent* events,
- int size) {
+void EventHandlerImplementation::HandleEvents(struct kevent* events, int size) {
bool interrupt_seen = false;
for (int i = 0; i < size; i++) {
// If flag EV_ERROR is set it indicates an error in kevent processing.
@@ -393,8 +379,7 @@
if (events[i].udata == NULL) {
interrupt_seen = true;
} else {
- DescriptorInfo* di =
- reinterpret_cast<DescriptorInfo*>(events[i].udata);
+ DescriptorInfo* di = reinterpret_cast<DescriptorInfo*>(events[i].udata);
intptr_t event_mask = GetEvents(events + i, di);
if ((event_mask & (1 << kErrorEvent)) != 0) {
di->NotifyAllDartPorts(event_mask);
@@ -422,8 +407,8 @@
if (!timeout_queue_.HasTimeout()) {
return kInfinityTimeout;
}
- int64_t millis = timeout_queue_.CurrentTimeout() -
- TimerUtils::GetCurrentMonotonicMillis();
+ int64_t millis =
+ timeout_queue_.CurrentTimeout() - TimerUtils::GetCurrentMonotonicMillis();
return (millis < 0) ? 0 : millis;
}
@@ -431,7 +416,7 @@
void EventHandlerImplementation::HandleTimeout() {
if (timeout_queue_.HasTimeout()) {
int64_t millis = timeout_queue_.CurrentTimeout() -
- TimerUtils::GetCurrentMonotonicMillis();
+ TimerUtils::GetCurrentMonotonicMillis();
if (millis <= 0) {
DartUtils::PostNull(timeout_queue_.CurrentPort());
timeout_queue_.RemoveCurrent();
@@ -483,9 +468,8 @@
void EventHandlerImplementation::Start(EventHandler* handler) {
- int result =
- Thread::Start(&EventHandlerImplementation::EventHandlerEntry,
- reinterpret_cast<uword>(handler));
+ int result = Thread::Start(&EventHandlerImplementation::EventHandlerEntry,
+ reinterpret_cast<uword>(handler));
if (result != 0) {
FATAL1("Failed to start event handler thread %d", result);
}
diff --git a/runtime/bin/eventhandler_macos.h b/runtime/bin/eventhandler_macos.h
index fbeac80..414dfbe 100644
--- a/runtime/bin/eventhandler_macos.h
+++ b/runtime/bin/eventhandler_macos.h
@@ -24,9 +24,9 @@
class DescriptorInfo : public DescriptorInfoBase {
public:
explicit DescriptorInfo(intptr_t fd)
- : DescriptorInfoBase(fd), tracked_by_kqueue_(false) { }
+ : DescriptorInfoBase(fd), tracked_by_kqueue_(false) {}
- virtual ~DescriptorInfo() { }
+ virtual ~DescriptorInfo() {}
intptr_t GetPollEvents();
@@ -35,9 +35,7 @@
fd_ = -1;
}
- void set_tracked_by_kqueue(bool value) {
- tracked_by_kqueue_ = value;
- }
+ void set_tracked_by_kqueue(bool value) { tracked_by_kqueue_ = value; }
bool tracked_by_kqueue() { return tracked_by_kqueue_; }
@@ -53,8 +51,7 @@
};
-class DescriptorInfoSingle
- : public DescriptorInfoSingleMixin<DescriptorInfo> {
+class DescriptorInfoSingle : public DescriptorInfoSingleMixin<DescriptorInfo> {
public:
explicit DescriptorInfoSingle(intptr_t fd)
: DescriptorInfoSingleMixin(fd, false) {}
@@ -82,7 +79,7 @@
EventHandlerImplementation();
~EventHandlerImplementation();
- void UpdateKQueueInstance(intptr_t old_mask, DescriptorInfo *di);
+ void UpdateKQueueInstance(intptr_t old_mask, DescriptorInfo* di);
// Gets the socket data structure for a given file
// descriptor. Creates a new one if one is not found.
diff --git a/runtime/bin/eventhandler_unsupported.cc b/runtime/bin/eventhandler_unsupported.cc
index c79ad24..e936055 100644
--- a/runtime/bin/eventhandler_unsupported.cc
+++ b/runtime/bin/eventhandler_unsupported.cc
@@ -13,24 +13,22 @@
namespace dart {
namespace bin {
-void EventHandler::Start() {
-}
+void EventHandler::Start() {}
-void EventHandler::Stop() {
-}
+void EventHandler::Stop() {}
void FUNCTION_NAME(EventHandler_SendData)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "EventHandler is not supported on this platform"));
+ "EventHandler is not supported on this platform"));
}
void FUNCTION_NAME(EventHandler_TimerMillisecondClock)(
Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "EventHandler is not supported on this platform"));
+ "EventHandler is not supported on this platform"));
}
} // namespace bin
diff --git a/runtime/bin/eventhandler_win.cc b/runtime/bin/eventhandler_win.cc
index f125bb8..81adcfd 100644
--- a/runtime/bin/eventhandler_win.cc
+++ b/runtime/bin/eventhandler_win.cc
@@ -10,9 +10,9 @@
#include "bin/eventhandler.h"
#include "bin/eventhandler_win.h"
-#include <fcntl.h> // NOLINT
-#include <io.h> // NOLINT
-#include <mswsock.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <io.h> // NOLINT
+#include <mswsock.h> // NOLINT
#include <winsock2.h> // NOLINT
#include <ws2tcpip.h> // NOLINT
@@ -36,7 +36,7 @@
OverlappedBuffer* OverlappedBuffer::AllocateBuffer(int buffer_size,
Operation operation) {
OverlappedBuffer* buffer =
- new(buffer_size) OverlappedBuffer(buffer_size, operation);
+ new (buffer_size) OverlappedBuffer(buffer_size, operation);
return buffer;
}
@@ -129,8 +129,7 @@
read_thread_handle_(NULL),
read_thread_starting_(false),
read_thread_finished_(false),
- monitor_(new Monitor()) {
-}
+ monitor_(new Monitor()) {}
Handle::~Handle() {
@@ -139,10 +138,8 @@
bool Handle::CreateCompletionPort(HANDLE completion_port) {
- completion_port_ = CreateIoCompletionPort(handle(),
- completion_port,
- reinterpret_cast<ULONG_PTR>(this),
- 0);
+ completion_port_ = CreateIoCompletionPort(
+ handle(), completion_port, reinterpret_cast<ULONG_PTR>(this), 0);
return (completion_port_ != NULL);
}
@@ -280,19 +277,14 @@
}
char* buffer_start = pending_read_->GetBufferStart();
DWORD bytes_read = 0;
- BOOL ok = ReadFile(handle_,
- buffer_start,
- buffer_size,
- &bytes_read,
- NULL);
+ BOOL ok = ReadFile(handle_, buffer_start, buffer_size, &bytes_read, NULL);
if (!ok) {
bytes_read = 0;
}
OVERLAPPED* overlapped = pending_read_->GetCleanOverlapped();
- ok = PostQueuedCompletionStatus(event_handler_->completion_port(),
- bytes_read,
- reinterpret_cast<ULONG_PTR>(this),
- overlapped);
+ ok =
+ PostQueuedCompletionStatus(event_handler_->completion_port(), bytes_read,
+ reinterpret_cast<ULONG_PTR>(this), overlapped);
if (!ok) {
FATAL("PostQueuedCompletionStatus failed");
}
@@ -307,11 +299,9 @@
if (SupportsOverlappedIO()) {
ASSERT(completion_port_ != INVALID_HANDLE_VALUE);
- BOOL ok = ReadFile(handle_,
- buffer->GetBufferStart(),
- buffer->GetBufferSize(),
- NULL,
- buffer->GetCleanOverlapped());
+ BOOL ok =
+ ReadFile(handle_, buffer->GetBufferStart(), buffer->GetBufferSize(),
+ NULL, buffer->GetCleanOverlapped());
if (ok || (GetLastError() == ERROR_IO_PENDING)) {
// Completing asynchronously.
pending_read_ = buffer;
@@ -324,8 +314,7 @@
// Completing asynchronously through thread.
pending_read_ = buffer;
read_thread_starting_ = true;
- int result = Thread::Start(ReadFileThread,
- reinterpret_cast<uword>(this));
+ int result = Thread::Start(ReadFileThread, reinterpret_cast<uword>(this));
if (result != 0) {
FATAL1("Failed to start read file thread %d", result);
}
@@ -347,11 +336,9 @@
ASSERT(pending_write_->operation() == OverlappedBuffer::kWrite);
OverlappedBuffer* buffer = pending_write_;
- BOOL ok = WriteFile(handle_,
- buffer->GetBufferStart(),
- buffer->GetBufferSize(),
- NULL,
- buffer->GetCleanOverlapped());
+ BOOL ok =
+ WriteFile(handle_, buffer->GetBufferStart(), buffer->GetBufferSize(),
+ NULL, buffer->GetCleanOverlapped());
if (ok || (GetLastError() == ERROR_IO_PENDING)) {
// Completing asynchronously.
pending_write_ = buffer;
@@ -433,14 +420,9 @@
}
OverlappedBuffer* buffer = OverlappedBuffer::AllocateReadBuffer(kBufferSize);
ASSERT(completion_port_ != INVALID_HANDLE_VALUE);
- BOOL ok = ReadDirectoryChangesW(handle_,
- buffer->GetBufferStart(),
- buffer->GetBufferSize(),
- recursive_,
- events_,
- NULL,
- buffer->GetCleanOverlapped(),
- NULL);
+ BOOL ok = ReadDirectoryChangesW(handle_, buffer->GetBufferStart(),
+ buffer->GetBufferSize(), recursive_, events_,
+ NULL, buffer->GetCleanOverlapped(), NULL);
if (ok || (GetLastError() == ERROR_IO_PENDING)) {
// Completing asynchronously.
pending_read_ = buffer;
@@ -479,15 +461,9 @@
// Load the AcceptEx function into memory using WSAIoctl.
GUID guid_accept_ex = WSAID_ACCEPTEX;
DWORD bytes;
- int status = WSAIoctl(socket(),
- SIO_GET_EXTENSION_FUNCTION_POINTER,
- &guid_accept_ex,
- sizeof(guid_accept_ex),
- &AcceptEx_,
- sizeof(AcceptEx_),
- &bytes,
- NULL,
- NULL);
+ int status = WSAIoctl(socket(), SIO_GET_EXTENSION_FUNCTION_POINTER,
+ &guid_accept_ex, sizeof(guid_accept_ex), &AcceptEx_,
+ sizeof(AcceptEx_), &bytes, NULL, NULL);
return (status != SOCKET_ERROR);
}
@@ -507,14 +483,10 @@
OverlappedBuffer::AllocateAcceptBuffer(2 * kAcceptExAddressStorageSize);
DWORD received;
BOOL ok;
- ok = AcceptEx_(socket(),
- buffer->client(),
- buffer->GetBufferStart(),
+ ok = AcceptEx_(socket(), buffer->client(), buffer->GetBufferStart(),
0, // For now don't receive data with accept.
- kAcceptExAddressStorageSize,
- kAcceptExAddressStorageSize,
- &received,
- buffer->GetCleanOverlapped());
+ kAcceptExAddressStorageSize, kAcceptExAddressStorageSize,
+ &received, buffer->GetCleanOverlapped());
if (!ok) {
if (WSAGetLastError() != WSA_IO_PENDING) {
int error = WSAGetLastError();
@@ -537,9 +509,7 @@
if (!IsClosing()) {
// Update the accepted socket to support the full range of API calls.
SOCKET s = socket();
- int rc = setsockopt(buffer->client(),
- SOL_SOCKET,
- SO_UPDATE_ACCEPT_CONTEXT,
+ int rc = setsockopt(buffer->client(), SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
reinterpret_cast<char*>(&s), sizeof(s));
if (rc == NO_ERROR) {
// Insert the accepted socket into the list.
@@ -582,7 +552,7 @@
handle_ = INVALID_HANDLE_VALUE;
while (CanAccept()) {
// Get rid of connections already accepted.
- ClientSocket *client = Accept();
+ ClientSocket* client = Accept();
if (client != NULL) {
client->Close();
DeleteIfClosed(client);
@@ -602,7 +572,7 @@
ClientSocket* ListenSocket::Accept() {
MonitorLocker ml(monitor_);
- ClientSocket *result = NULL;
+ ClientSocket* result = NULL;
if (accepted_head_ != NULL) {
result = accepted_head_;
@@ -660,8 +630,8 @@
if (data_ready_ == NULL) {
return 0;
}
- num_bytes = data_ready_->Read(
- buffer, Utils::Minimum<intptr_t>(num_bytes, INT_MAX));
+ num_bytes =
+ data_ready_->Read(buffer, Utils::Minimum<intptr_t>(num_bytes, INT_MAX));
if (data_ready_->IsEmpty()) {
OverlappedBuffer::DisposeBuffer(data_ready_);
data_ready_ = NULL;
@@ -673,14 +643,16 @@
}
-intptr_t Handle::RecvFrom(
- void* buffer, intptr_t num_bytes, struct sockaddr* sa, socklen_t sa_len) {
+intptr_t Handle::RecvFrom(void* buffer,
+ intptr_t num_bytes,
+ struct sockaddr* sa,
+ socklen_t sa_len) {
MonitorLocker ml(monitor_);
if (data_ready_ == NULL) {
return 0;
}
- num_bytes = data_ready_->Read(
- buffer, Utils::Minimum<intptr_t>(num_bytes, INT_MAX));
+ num_bytes =
+ data_ready_->Read(buffer, Utils::Minimum<intptr_t>(num_bytes, INT_MAX));
if (data_ready_->from()->sa_family == AF_INET) {
ASSERT(sa_len >= sizeof(struct sockaddr_in));
memmove(sa, data_ready_->from(), sizeof(struct sockaddr_in));
@@ -777,20 +749,16 @@
ASSERT(pending_write_ != NULL);
DWORD bytes_written = -1;
- BOOL ok = WriteFile(handle_,
- pending_write_->GetBufferStart(),
- pending_write_->GetBufferSize(),
- &bytes_written,
- NULL);
+ BOOL ok = WriteFile(handle_, pending_write_->GetBufferStart(),
+ pending_write_->GetBufferSize(), &bytes_written, NULL);
if (!ok) {
bytes_written = 0;
}
thread_wrote_ += bytes_written;
OVERLAPPED* overlapped = pending_write_->GetCleanOverlapped();
- ok = PostQueuedCompletionStatus(event_handler_->completion_port(),
- bytes_written,
- reinterpret_cast<ULONG_PTR>(this),
- overlapped);
+ ok = PostQueuedCompletionStatus(
+ event_handler_->completion_port(), bytes_written,
+ reinterpret_cast<ULONG_PTR>(this), overlapped);
if (!ok) {
FATAL("PostQueuedCompletionStatus failed");
}
@@ -818,8 +786,7 @@
}
if (!write_thread_exists_) {
write_thread_exists_ = true;
- int result = Thread::Start(
- WriteFileThread, reinterpret_cast<uword>(this));
+ int result = Thread::Start(WriteFileThread, reinterpret_cast<uword>(this));
if (result != 0) {
FATAL1("Failed to start write file thread %d", result);
}
@@ -859,15 +826,10 @@
// Load the DisconnectEx function into memory using WSAIoctl.
GUID guid_disconnect_ex = WSAID_DISCONNECTEX;
DWORD bytes;
- int status = WSAIoctl(socket(),
- SIO_GET_EXTENSION_FUNCTION_POINTER,
- &guid_disconnect_ex,
- sizeof(guid_disconnect_ex),
- &DisconnectEx_,
- sizeof(DisconnectEx_),
- &bytes,
- NULL,
- NULL);
+ int status =
+ WSAIoctl(socket(), SIO_GET_EXTENSION_FUNCTION_POINTER,
+ &guid_disconnect_ex, sizeof(guid_disconnect_ex), &DisconnectEx_,
+ sizeof(DisconnectEx_), &bytes, NULL, NULL);
return (status != SOCKET_ERROR);
}
@@ -906,13 +868,8 @@
DWORD flags;
flags = 0;
- int rc = WSARecv(socket(),
- buffer->GetWASBUF(),
- 1,
- NULL,
- &flags,
- buffer->GetCleanOverlapped(),
- NULL);
+ int rc = WSARecv(socket(), buffer->GetWASBUF(), 1, NULL, &flags,
+ buffer->GetCleanOverlapped(), NULL);
if ((rc == NO_ERROR) || (WSAGetLastError() == WSA_IO_PENDING)) {
pending_read_ = buffer;
return true;
@@ -930,13 +887,8 @@
ASSERT(pending_write_ != NULL);
ASSERT(pending_write_->operation() == OverlappedBuffer::kWrite);
- int rc = WSASend(socket(),
- pending_write_->GetWASBUF(),
- 1,
- NULL,
- 0,
- pending_write_->GetCleanOverlapped(),
- NULL);
+ int rc = WSASend(socket(), pending_write_->GetWASBUF(), 1, NULL, 0,
+ pending_write_->GetCleanOverlapped(), NULL);
if ((rc == NO_ERROR) || (WSAGetLastError() == WSA_IO_PENDING)) {
return true;
}
@@ -949,8 +901,8 @@
void ClientSocket::IssueDisconnect() {
OverlappedBuffer* buffer = OverlappedBuffer::AllocateDisconnectBuffer();
- BOOL ok = DisconnectEx_(
- socket(), buffer->GetCleanOverlapped(), TF_REUSE_SOCKET, 0);
+ BOOL ok =
+ DisconnectEx_(socket(), buffer->GetCleanOverlapped(), TF_REUSE_SOCKET, 0);
// DisconnectEx works like other OverlappedIO APIs, where we can get either an
// immediate success or delayed operation by WSA_IO_PENDING being set.
if (ok || (WSAGetLastError() != WSA_IO_PENDING)) {
@@ -1009,15 +961,8 @@
ASSERT(pending_write_ != NULL);
ASSERT(pending_write_->operation() == OverlappedBuffer::kSendTo);
- int rc = WSASendTo(socket(),
- pending_write_->GetWASBUF(),
- 1,
- NULL,
- 0,
- sa,
- sa_len,
- pending_write_->GetCleanOverlapped(),
- NULL);
+ int rc = WSASendTo(socket(), pending_write_->GetWASBUF(), 1, NULL, 0, sa,
+ sa_len, pending_write_->GetCleanOverlapped(), NULL);
if ((rc == NO_ERROR) || (WSAGetLastError() == WSA_IO_PENDING)) {
return true;
}
@@ -1038,15 +983,9 @@
DWORD flags;
flags = 0;
- int rc = WSARecvFrom(socket(),
- buffer->GetWASBUF(),
- 1,
- NULL,
- &flags,
- buffer->from(),
- buffer->from_len_addr(),
- buffer->GetCleanOverlapped(),
- NULL);
+ int rc = WSARecvFrom(socket(), buffer->GetWASBUF(), 1, NULL, &flags,
+ buffer->from(), buffer->from_len_addr(),
+ buffer->GetCleanOverlapped(), NULL);
if ((rc == NO_ERROR) || (WSAGetLastError() == WSA_IO_PENDING)) {
pending_read_ = buffer;
return true;
@@ -1096,8 +1035,7 @@
ASSERT(handle != NULL);
if (handle->is_listen_socket()) {
- ListenSocket* listen_socket =
- reinterpret_cast<ListenSocket*>(handle);
+ ListenSocket* listen_socket = reinterpret_cast<ListenSocket*>(handle);
listen_socket->EnsureInitialized(this);
MonitorLocker ml(listen_socket->monitor_);
@@ -1116,8 +1054,7 @@
// We only close the socket file descriptor from the operating
// system if there are no other dart socket objects which
// are listening on the same (address, port) combination.
- ListeningSocketRegistry *registry =
- ListeningSocketRegistry::Instance();
+ ListeningSocketRegistry* registry = ListeningSocketRegistry::Instance();
MutexLocker locker(registry->mutex());
if (registry->CloseSafe(reinterpret_cast<intptr_t>(listen_socket))) {
ASSERT(listen_socket->Mask() == 0);
@@ -1213,12 +1150,11 @@
void EventHandlerImplementation::TryDispatchingPendingAccepts(
- ListenSocket *listen_socket) {
+ ListenSocket* listen_socket) {
if (!listen_socket->IsClosing() && listen_socket->CanAccept()) {
intptr_t event_mask = 1 << kInEvent;
- for (int i = 0;
- (i < listen_socket->accepted_count()) &&
- (listen_socket->Mask() == event_mask);
+ for (int i = 0; (i < listen_socket->accepted_count()) &&
+ (listen_socket->Mask() == event_mask);
i++) {
Dart_Port port = listen_socket->NextNotifyDartPort(event_mask);
DartUtils::PostInt32(port, event_mask);
@@ -1298,19 +1234,17 @@
}
-void EventHandlerImplementation::HandleDisconnect(
- ClientSocket* client_socket,
- int bytes,
- OverlappedBuffer* buffer) {
+void EventHandlerImplementation::HandleDisconnect(ClientSocket* client_socket,
+ int bytes,
+ OverlappedBuffer* buffer) {
client_socket->DisconnectComplete(buffer);
DeleteIfClosed(client_socket);
}
-void EventHandlerImplementation::HandleConnect(
- ClientSocket* client_socket,
- int bytes,
- OverlappedBuffer* buffer) {
+void EventHandlerImplementation::HandleConnect(ClientSocket* client_socket,
+ int bytes,
+ OverlappedBuffer* buffer) {
if (bytes < 0) {
HandleError(client_socket);
OverlappedBuffer::DisposeBuffer(buffer);
@@ -1400,8 +1334,8 @@
if (!timeout_queue_.HasTimeout()) {
return kInfinityTimeout;
}
- int64_t millis = timeout_queue_.CurrentTimeout() -
- TimerUtils::GetCurrentMonotonicMillis();
+ int64_t millis =
+ timeout_queue_.CurrentTimeout() - TimerUtils::GetCurrentMonotonicMillis();
return (millis < 0) ? 0 : millis;
}
@@ -1413,8 +1347,8 @@
msg->id = id;
msg->dart_port = dart_port;
msg->data = data;
- BOOL ok = PostQueuedCompletionStatus(
- completion_port_, 0, NULL, reinterpret_cast<OVERLAPPED*>(msg));
+ BOOL ok = PostQueuedCompletionStatus(completion_port_, 0, NULL,
+ reinterpret_cast<OVERLAPPED*>(msg));
if (!ok) {
FATAL("PostQueuedCompletionStatus failed");
}
@@ -1444,11 +1378,9 @@
millis = kMaxInt32;
}
ASSERT(sizeof(int32_t) == sizeof(DWORD));
- BOOL ok = GetQueuedCompletionStatus(handler_impl->completion_port(),
- &bytes,
- &key,
- &overlapped,
- static_cast<DWORD>(millis));
+ BOOL ok =
+ GetQueuedCompletionStatus(handler_impl->completion_port(), &bytes, &key,
+ &overlapped, static_cast<DWORD>(millis));
if (!ok && (overlapped == NULL)) {
if (GetLastError() == ERROR_ABANDONED_WAIT_0) {
@@ -1495,8 +1427,8 @@
void EventHandlerImplementation::Start(EventHandler* handler) {
- int result = Thread::Start(EventHandlerEntry,
- reinterpret_cast<uword>(handler));
+ int result =
+ Thread::Start(EventHandlerEntry, reinterpret_cast<uword>(handler));
if (result != 0) {
FATAL1("Failed to start event handler thread %d", result);
}
diff --git a/runtime/bin/eventhandler_win.h b/runtime/bin/eventhandler_win.h
index 4ad7501..7795ac9 100644
--- a/runtime/bin/eventhandler_win.h
+++ b/runtime/bin/eventhandler_win.h
@@ -33,7 +33,13 @@
class OverlappedBuffer {
public:
enum Operation {
- kAccept, kRead, kRecvFrom, kWrite, kSendTo, kDisconnect, kConnect
+ kAccept,
+ kRead,
+ kRecvFrom,
+ kWrite,
+ kSendTo,
+ kDisconnect,
+ kConnect
};
static OverlappedBuffer* AllocateAcceptBuffer(int buffer_size);
@@ -68,7 +74,9 @@
SOCKET client() { return client_; }
char* GetBufferStart() { return reinterpret_cast<char*>(&buffer_data_); }
int GetBufferSize() { return buflen_; }
- struct sockaddr* from() { return from_; }
+ struct sockaddr* from() {
+ return from_;
+ }
socklen_t* from_len_addr() { return from_len_addr_; }
socklen_t from_len() { return from_ == NULL ? 0 : *from_len_addr_; }
@@ -99,8 +107,8 @@
sizeof(struct sockaddr_storage) + sizeof(socklen_t);
ASSERT(buflen_ > kAdditionalSize);
buflen_ -= kAdditionalSize;
- from_len_addr_ = reinterpret_cast<socklen_t*>(
- GetBufferStart() + GetBufferSize());
+ from_len_addr_ =
+ reinterpret_cast<socklen_t*>(GetBufferStart() + GetBufferSize());
*from_len_addr_ = sizeof(struct sockaddr_storage);
from_ = reinterpret_cast<struct sockaddr*>(from_len_addr_ + 1);
} else {
@@ -118,22 +126,19 @@
return malloc(size + buffer_size);
}
- void operator delete(void* buffer) {
- free(buffer);
- }
+ void operator delete(void* buffer) { free(buffer); }
// Allocate an overlapped buffer for thse specified amount of data and
// operation. Some operations need additional buffer space, which is
// handled by this method.
- static OverlappedBuffer* AllocateBuffer(int buffer_size,
- Operation operation);
+ static OverlappedBuffer* AllocateBuffer(int buffer_size, Operation operation);
OVERLAPPED overlapped_; // OVERLAPPED structure for overlapped IO.
- SOCKET client_; // Used for AcceptEx client socket.
- int buflen_; // Length of the buffer.
- Operation operation_; // Type of operation issued.
+ SOCKET client_; // Used for AcceptEx client socket.
+ int buflen_; // Length of the buffer.
+ Operation operation_; // Type of operation issued.
- int index_; // Index for next read from read buffer.
+ int index_; // Index for next read from read buffer.
int data_length_; // Length of the actual data in the buffer.
WSABUF wbuf_; // Structure for passing buffer to WSA functions.
@@ -141,7 +146,7 @@
// For the recvfrom operation additional storace is allocated for the
// source sockaddr.
socklen_t* from_len_addr_; // Pointer to source sockaddr size storage.
- struct sockaddr* from_; // Pointer to source sockaddr storage.
+ struct sockaddr* from_; // Pointer to source sockaddr storage.
// Buffer for recv/send/AcceptEx. This must be at the end of the
// object as the object is allocated larger than it's definition
@@ -200,8 +205,7 @@
void MarkClosedWrite() { flags_ |= (1 << kCloseWrite); }
void MarkError() { flags_ |= (1 << kError); }
- virtual void EnsureInitialized(
- EventHandlerImplementation* event_handler) = 0;
+ virtual void EnsureInitialized(EventHandlerImplementation* event_handler) = 0;
HANDLE handle() { return handle_; }
@@ -215,9 +219,10 @@
Type type() { return type_; }
bool is_file() { return type_ == kFile; }
- bool is_socket() { return type_ == kListenSocket ||
- type_ == kClientSocket ||
- type_ == kDatagramSocket; }
+ bool is_socket() {
+ return type_ == kListenSocket || type_ == kClientSocket ||
+ type_ == kDatagramSocket;
+ }
bool is_listen_socket() { return type_ == kListenSocket; }
bool is_client_socket() { return type_ == kClientSocket; }
bool is_datagram_socket() { return type_ == kDatagramSocket; }
@@ -256,8 +261,8 @@
HANDLE completion_port_;
EventHandlerImplementation* event_handler_;
- OverlappedBuffer* data_ready_; // Buffer for data ready to be read.
- OverlappedBuffer* pending_read_; // Buffer for pending read.
+ OverlappedBuffer* data_ready_; // Buffer for data ready to be read.
+ OverlappedBuffer* pending_read_; // Buffer for pending read.
OverlappedBuffer* pending_write_; // Buffer for pending write
DWORD last_error_;
@@ -352,9 +357,7 @@
SOCKET socket() const { return socket_; }
protected:
- explicit SocketHandle(intptr_t s)
- : Handle(s),
- socket_(s) {}
+ explicit SocketHandle(intptr_t s) : Handle(s), socket_(s) {}
virtual void HandleIssueError();
@@ -368,12 +371,13 @@
// Information on listen sockets.
class ListenSocket : public DescriptorInfoMultipleMixin<SocketHandle> {
public:
- explicit ListenSocket(intptr_t s) : DescriptorInfoMultipleMixin(s, true),
- AcceptEx_(NULL),
- pending_accept_count_(0),
- accepted_head_(NULL),
- accepted_tail_(NULL),
- accepted_count_(0) {
+ explicit ListenSocket(intptr_t s)
+ : DescriptorInfoMultipleMixin(s, true),
+ AcceptEx_(NULL),
+ pending_accept_count_(0),
+ accepted_head_(NULL),
+ accepted_tail_(NULL),
+ accepted_count_(0) {
type_ = kListenSocket;
}
virtual ~ListenSocket() {
@@ -391,8 +395,7 @@
bool IssueAccept();
void AcceptComplete(OverlappedBuffer* buffer, HANDLE completion_port);
- virtual void EnsureInitialized(
- EventHandlerImplementation* event_handler);
+ virtual void EnsureInitialized(EventHandlerImplementation* event_handler);
virtual void DoClose();
virtual bool IsClosed();
@@ -425,11 +428,12 @@
// Information on connected sockets.
class ClientSocket : public DescriptorInfoSingleMixin<SocketHandle> {
public:
- explicit ClientSocket(intptr_t s) : DescriptorInfoSingleMixin(s, true),
- DisconnectEx_(NULL),
- next_(NULL),
- connected_(false),
- closed_(false) {
+ explicit ClientSocket(intptr_t s)
+ : DescriptorInfoSingleMixin(s, true),
+ DisconnectEx_(NULL),
+ next_(NULL),
+ connected_(false),
+ closed_(false) {
LoadDisconnectEx();
type_ = kClientSocket;
}
@@ -452,22 +456,17 @@
void ConnectComplete(OverlappedBuffer* buffer);
- virtual void EnsureInitialized(
- EventHandlerImplementation* event_handler);
+ virtual void EnsureInitialized(EventHandlerImplementation* event_handler);
virtual void DoClose();
virtual bool IsClosed();
ClientSocket* next() { return next_; }
void set_next(ClientSocket* next) { next_ = next; }
- void mark_connected() {
- connected_ = true;
- }
+ void mark_connected() { connected_ = true; }
bool is_connected() const { return connected_; }
- void mark_closed() {
- closed_ = true;
- }
+ void mark_closed() { closed_ = true; }
private:
bool LoadDisconnectEx();
@@ -522,7 +521,7 @@
void HandleInterrupt(InterruptMessage* msg);
void HandleTimeout();
void HandleAccept(ListenSocket* listen_socket, OverlappedBuffer* buffer);
- void TryDispatchingPendingAccepts(ListenSocket *listen_socket);
+ void TryDispatchingPendingAccepts(ListenSocket* listen_socket);
void HandleRead(Handle* handle, int bytes, OverlappedBuffer* buffer);
void HandleRecvFrom(Handle* handle, int bytes, OverlappedBuffer* buffer);
void HandleWrite(Handle* handle, int bytes, OverlappedBuffer* buffer);
diff --git a/runtime/bin/extensions.cc b/runtime/bin/extensions.cc
index 4584d01..fd0961f 100644
--- a/runtime/bin/extensions.cc
+++ b/runtime/bin/extensions.cc
@@ -28,14 +28,14 @@
// First try to find the library with a suffix specifying the architecture.
{
const char* path_components[] = {
- dir,
- Platform::LibraryPrefix(),
- name,
- "-",
- Platform::HostArchitecture(), // arm
- ".",
- Platform::LibraryExtension(), // so
- NULL,
+ dir,
+ Platform::LibraryPrefix(),
+ name,
+ "-",
+ Platform::HostArchitecture(), // arm
+ ".",
+ Platform::LibraryExtension(), // so
+ NULL,
};
const char* library_file = Concatenate(path_components);
void* library_handle = LoadExtensionLibrary(library_file);
@@ -47,12 +47,12 @@
// Fall back on a library name without the suffix.
{
const char* path_components[] = {
- dir,
- Platform::LibraryPrefix(),
- name,
- ".",
- Platform::LibraryExtension(), // so
- NULL,
+ dir,
+ Platform::LibraryPrefix(),
+ name,
+ ".",
+ Platform::LibraryExtension(), // so
+ NULL,
};
const char* library_file = Concatenate(path_components);
return LoadExtensionLibrary(library_file);
@@ -85,8 +85,8 @@
// If the path following dart-ext is just a file name, first look next to
// the importing Dart library.
- void* library_handle = MakePathAndResolve(extension_directory,
- extension_name);
+ void* library_handle =
+ MakePathAndResolve(extension_directory, extension_name);
if (library_handle != NULL) {
return library_handle;
}
@@ -110,7 +110,7 @@
extension = strrchr(extension_name, PathSeparator()) + 1;
}
- const char* strings[] = { extension, "_Init", NULL };
+ const char* strings[] = {extension, "_Init", NULL};
const char* init_function_name = Concatenate(strings);
void* init_function = ResolveSymbol(library_handle, init_function_name);
Dart_Handle result = GetError();
diff --git a/runtime/bin/fdutils_android.cc b/runtime/bin/fdutils_android.cc
index 3c22a04..e61a2e1 100644
--- a/runtime/bin/fdutils_android.cc
+++ b/runtime/bin/fdutils_android.cc
@@ -7,10 +7,10 @@
#include "bin/fdutils.h"
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
#include <sys/ioctl.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "platform/signal_blocker.h"
diff --git a/runtime/bin/fdutils_linux.cc b/runtime/bin/fdutils_linux.cc
index f80356e..a76fcdb 100644
--- a/runtime/bin/fdutils_linux.cc
+++ b/runtime/bin/fdutils_linux.cc
@@ -7,10 +7,10 @@
#include "bin/fdutils.h"
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
#include <sys/ioctl.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "platform/signal_blocker.h"
diff --git a/runtime/bin/fdutils_macos.cc b/runtime/bin/fdutils_macos.cc
index 41f1d24..25495da 100644
--- a/runtime/bin/fdutils_macos.cc
+++ b/runtime/bin/fdutils_macos.cc
@@ -7,10 +7,10 @@
#include "bin/fdutils.h"
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
#include <sys/ioctl.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "platform/signal_blocker.h"
diff --git a/runtime/bin/file.cc b/runtime/bin/file.cc
index 828db76..ee3255a 100644
--- a/runtime/bin/file.cc
+++ b/runtime/bin/file.cc
@@ -28,19 +28,15 @@
File* file;
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
ASSERT(Dart_IsInstance(dart_this));
- ThrowIfError(Dart_GetNativeInstanceField(
- dart_this,
- kFileNativeFieldIndex,
- reinterpret_cast<intptr_t*>(&file)));
+ ThrowIfError(Dart_GetNativeInstanceField(dart_this, kFileNativeFieldIndex,
+ reinterpret_cast<intptr_t*>(&file)));
return file;
}
static void SetFile(Dart_Handle dart_this, intptr_t file_pointer) {
Dart_Handle result = Dart_SetNativeInstanceField(
- dart_this,
- kFileNativeFieldIndex,
- file_pointer);
+ dart_this, kFileNativeFieldIndex, file_pointer);
if (Dart_IsError(result)) {
Log::PrintErr("SetNativeInstanceField in SetFile() failed\n");
Dart_PropagateError(result);
@@ -183,10 +179,8 @@
Dart_PropagateError(io_lib);
}
Dart_Handle array_view =
- Dart_Invoke(io_lib,
- DartUtils::NewString("_makeUint8ListView"),
- kNumArgs,
- dart_args);
+ Dart_Invoke(io_lib, DartUtils::NewString("_makeUint8ListView"),
+ kNumArgs, dart_args);
Dart_SetReturnValue(args, array_view);
} else {
Dart_SetReturnValue(args, external_array);
@@ -208,10 +202,8 @@
// integers and have the property that end <=
// list.length. Therefore, it is safe to extract their value as
// intptr_t.
- intptr_t start =
- DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 2));
- intptr_t end =
- DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 3));
+ intptr_t start = DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 2));
+ intptr_t end = DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 3));
intptr_t length = end - start;
intptr_t array_len = 0;
Dart_Handle result = Dart_ListLength(buffer_obj, &array_len);
@@ -244,10 +236,8 @@
// integers and have the property that (offset + length) <=
// list.length. Therefore, it is safe to extract their value as
// intptr_t.
- intptr_t start =
- DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 2));
- intptr_t end =
- DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 3));
+ intptr_t start = DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 2));
+ intptr_t end = DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 3));
// The buffer object passed in has to be an Int8List or Uint8List object.
// Acquire a direct pointer to the data area of the buffer object.
@@ -341,8 +331,7 @@
void FUNCTION_NAME(File_LengthFromPath)(Dart_NativeArguments args) {
- const char* path =
- DartUtils::GetStringValue(Dart_GetNativeArgument(args, 0));
+ const char* path = DartUtils::GetStringValue(Dart_GetNativeArgument(args, 0));
int64_t return_value = File::LengthFromPath(path);
if (return_value >= 0) {
Dart_SetReturnValue(args, Dart_NewInteger(return_value));
@@ -353,8 +342,7 @@
void FUNCTION_NAME(File_LastModified)(Dart_NativeArguments args) {
- const char* name =
- DartUtils::GetStringValue(Dart_GetNativeArgument(args, 0));
+ const char* name = DartUtils::GetStringValue(Dart_GetNativeArgument(args, 0));
int64_t return_value = File::LastModified(name);
if (return_value >= 0) {
Dart_SetReturnValue(args, Dart_NewInteger(return_value * kMSPerSecond));
@@ -384,8 +372,8 @@
if (DartUtils::GetInt64Value(Dart_GetNativeArgument(args, 1), &lock) &&
DartUtils::GetInt64Value(Dart_GetNativeArgument(args, 2), &start) &&
DartUtils::GetInt64Value(Dart_GetNativeArgument(args, 3), &end)) {
- if ((lock >= File::kLockMin) && (lock <= File::kLockMax) &&
- (start >= 0) && (end == -1 || end > start)) {
+ if ((lock >= File::kLockMin) && (lock <= File::kLockMax) && (start >= 0) &&
+ (end == -1 || end > start)) {
if (file->Lock(static_cast<File::LockType>(lock), start, end)) {
Dart_SetReturnValue(args, Dart_True());
} else {
@@ -400,8 +388,7 @@
void FUNCTION_NAME(File_Create)(Dart_NativeArguments args) {
- const char* str =
- DartUtils::GetStringValue(Dart_GetNativeArgument(args, 0));
+ const char* str = DartUtils::GetStringValue(Dart_GetNativeArgument(args, 0));
bool result = File::Create(str);
if (result) {
Dart_SetReturnValue(args, Dart_NewBoolean(result));
@@ -421,9 +408,9 @@
if (!File::CreateLink(name, target)) {
Dart_SetReturnValue(args, DartUtils::NewDartOSError());
}
- } else {
- Dart_Handle err = DartUtils::NewDartArgumentError(
- "Non-string argument to Link.create");
+ } else {
+ Dart_Handle err =
+ DartUtils::NewDartArgumentError("Non-string argument to Link.create");
Dart_SetReturnValue(args, err);
}
}
@@ -440,16 +427,15 @@
Dart_SetReturnValue(args, DartUtils::NewString(target));
}
} else {
- Dart_Handle err = DartUtils::NewDartArgumentError(
- "Non-string argument to Link.target");
+ Dart_Handle err =
+ DartUtils::NewDartArgumentError("Non-string argument to Link.target");
Dart_SetReturnValue(args, err);
}
}
void FUNCTION_NAME(File_Delete)(Dart_NativeArguments args) {
- const char* str =
- DartUtils::GetStringValue(Dart_GetNativeArgument(args, 0));
+ const char* str = DartUtils::GetStringValue(Dart_GetNativeArgument(args, 0));
bool result = File::Delete(str);
if (result) {
Dart_SetReturnValue(args, Dart_NewBoolean(result));
@@ -460,8 +446,7 @@
void FUNCTION_NAME(File_DeleteLink)(Dart_NativeArguments args) {
- const char* str =
- DartUtils::GetStringValue(Dart_GetNativeArgument(args, 0));
+ const char* str = DartUtils::GetStringValue(Dart_GetNativeArgument(args, 0));
bool result = File::DeleteLink(str);
if (result) {
Dart_SetReturnValue(args, Dart_NewBoolean(result));
@@ -514,8 +499,7 @@
void FUNCTION_NAME(File_ResolveSymbolicLinks)(Dart_NativeArguments args) {
- const char* str =
- DartUtils::GetStringValue(Dart_GetNativeArgument(args, 0));
+ const char* str = DartUtils::GetStringValue(Dart_GetNativeArgument(args, 0));
const char* path = File::GetCanonicalPath(str);
if (path != NULL) {
Dart_SetReturnValue(args, DartUtils::NewString(path));
@@ -527,8 +511,7 @@
void FUNCTION_NAME(File_OpenStdio)(Dart_NativeArguments args) {
int64_t fd = DartUtils::GetIntegerValue(Dart_GetNativeArgument(args, 0));
- ASSERT((fd == STDIN_FILENO) ||
- (fd == STDOUT_FILENO) ||
+ ASSERT((fd == STDIN_FILENO) || (fd == STDOUT_FILENO) ||
(fd == STDERR_FILENO));
File* file = File::OpenStdio(static_cast<int>(fd));
Dart_SetReturnValue(args, Dart_NewInteger(reinterpret_cast<intptr_t>(file)));
@@ -537,8 +520,7 @@
void FUNCTION_NAME(File_GetStdioHandleType)(Dart_NativeArguments args) {
int64_t fd = DartUtils::GetIntegerValue(Dart_GetNativeArgument(args, 0));
- ASSERT((fd == STDIN_FILENO) ||
- (fd == STDOUT_FILENO) ||
+ ASSERT((fd == STDIN_FILENO) || (fd == STDOUT_FILENO) ||
(fd == STDERR_FILENO));
File::StdioHandleType type = File::GetStdioHandleType(static_cast<int>(fd));
Dart_SetReturnValue(args, Dart_NewInteger(type));
@@ -554,7 +536,7 @@
DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 1));
File::Type type = File::GetType(str, follow_links);
Dart_SetReturnValue(args, Dart_NewInteger(static_cast<int>(type)));
- } else {
+ } else {
Dart_Handle err = DartUtils::NewDartArgumentError(
"Non-string argument to FileSystemEntity.type");
Dart_SetReturnValue(args, err);
@@ -572,18 +554,17 @@
if (stat_data[File::kType] == File::kDoesNotExist) {
Dart_SetReturnValue(args, DartUtils::NewDartOSError());
} else {
- Dart_Handle returned_data = Dart_NewTypedData(Dart_TypedData_kInt64,
- File::kStatSize);
+ Dart_Handle returned_data =
+ Dart_NewTypedData(Dart_TypedData_kInt64, File::kStatSize);
if (Dart_IsError(returned_data)) {
Dart_PropagateError(returned_data);
}
Dart_TypedData_Type data_type_unused;
void* data_location;
intptr_t data_length_unused;
- Dart_Handle status = Dart_TypedDataAcquireData(returned_data,
- &data_type_unused,
- &data_location,
- &data_length_unused);
+ Dart_Handle status =
+ Dart_TypedDataAcquireData(returned_data, &data_type_unused,
+ &data_location, &data_length_unused);
if (Dart_IsError(status)) {
Dart_PropagateError(status);
}
@@ -615,7 +596,7 @@
} else {
Dart_SetReturnValue(args, Dart_NewBoolean(result == File::kIdentical));
}
- } else {
+ } else {
Dart_Handle err = DartUtils::NewDartArgumentError(
"Non-string argument to FileSystemEntity.identical");
Dart_SetReturnValue(args, err);
@@ -669,8 +650,7 @@
CObject* File::OpenRequest(const CObjectArray& request) {
File* file = NULL;
- if ((request.Length() == 2) &&
- request[0]->IsString() &&
+ if ((request.Length() == 2) && request[0]->IsString() &&
request[1]->IsInt32()) {
CObjectString filename(request[0]);
CObjectInt32 mode(request[1]);
@@ -704,8 +684,7 @@
CObject* File::RenameRequest(const CObjectArray& request) {
- if ((request.Length() == 2) &&
- request[0]->IsString() &&
+ if ((request.Length() == 2) && request[0]->IsString() &&
request[1]->IsString()) {
CObjectString old_path(request[0]);
CObjectString new_path(request[1]);
@@ -720,8 +699,7 @@
CObject* File::CopyRequest(const CObjectArray& request) {
- if ((request.Length() == 2) &&
- request[0]->IsString() &&
+ if ((request.Length() == 2) && request[0]->IsString() &&
request[1]->IsString()) {
CObjectString old_path(request[0]);
CObjectString new_path(request[1]);
@@ -1046,8 +1024,7 @@
RefCntReleaseScope<File> rs(file);
if ((request.Length() == 4) &&
(request[1]->IsTypedData() || request[1]->IsArray()) &&
- request[2]->IsInt32OrInt64() &&
- request[3]->IsInt32OrInt64()) {
+ request[2]->IsInt32OrInt64() && request[3]->IsInt32OrInt64()) {
if (!file->IsClosed()) {
int64_t start = CObjectInt32OrInt64ToInt64(request[2]);
int64_t end = CObjectInt32OrInt64ToInt64(request[3]);
@@ -1091,8 +1068,7 @@
CObject* File::CreateLinkRequest(const CObjectArray& request) {
- if ((request.Length() != 2) ||
- !request[0]->IsString() ||
+ if ((request.Length() != 2) || !request[0]->IsString() ||
!request[1]->IsString()) {
return CObject::IllegalArgumentError();
}
@@ -1121,8 +1097,7 @@
CObject* File::RenameLinkRequest(const CObjectArray& request) {
- if ((request.Length() == 2) &&
- request[0]->IsString() &&
+ if ((request.Length() == 2) && request[0]->IsString() &&
request[1]->IsString()) {
CObjectString old_path(request[0]);
CObjectString new_path(request[1]);
@@ -1152,8 +1127,7 @@
CObject* File::TypeRequest(const CObjectArray& request) {
- if ((request.Length() == 2) &&
- request[0]->IsString() &&
+ if ((request.Length() == 2) && request[0]->IsString() &&
request[1]->IsBool()) {
CObjectString path(request[0]);
CObjectBool follow_links(request[1]);
@@ -1165,13 +1139,12 @@
CObject* File::IdenticalRequest(const CObjectArray& request) {
- if ((request.Length() == 2) &&
- request[0]->IsString() &&
+ if ((request.Length() == 2) && request[0]->IsString() &&
request[1]->IsString()) {
CObjectString path1(request[0]);
CObjectString path2(request[1]);
- File::Identical result = File::AreIdentical(path1.CString(),
- path2.CString());
+ File::Identical result =
+ File::AreIdentical(path1.CString(), path2.CString());
if (result == File::kError) {
return CObject::NewOSError();
} else if (result == File::kIdentical) {
@@ -1192,8 +1165,7 @@
if (data[File::kType] == File::kDoesNotExist) {
return CObject::NewOSError();
}
- CObjectArray* result =
- new CObjectArray(CObject::NewArray(File::kStatSize));
+ CObjectArray* result = new CObjectArray(CObject::NewArray(File::kStatSize));
for (int i = 0; i < File::kStatSize; ++i) {
result->SetAt(i, new CObjectInt64(CObject::NewInt64(data[i])));
}
@@ -1210,10 +1182,8 @@
if ((request.Length() >= 1) && request[0]->IsIntptr()) {
File* file = CObjectToFilePointer(request[0]);
RefCntReleaseScope<File> rs(file);
- if ((request.Length() == 4) &&
- request[1]->IsInt32OrInt64() &&
- request[2]->IsInt32OrInt64() &&
- request[3]->IsInt32OrInt64()) {
+ if ((request.Length() == 4) && request[1]->IsInt32OrInt64() &&
+ request[2]->IsInt32OrInt64() && request[3]->IsInt32OrInt64()) {
if (!file->IsClosed()) {
int64_t lock = CObjectInt32OrInt64ToInt64(request[1]);
int64_t start = CObjectInt32OrInt64ToInt64(request[2]);
diff --git a/runtime/bin/file.h b/runtime/bin/file.h
index 3cce143..300e561 100644
--- a/runtime/bin/file.h
+++ b/runtime/bin/file.h
@@ -43,18 +43,9 @@
kDartWriteOnlyAppend = 4
};
- enum Type {
- kIsFile = 0,
- kIsDirectory = 1,
- kIsLink = 2,
- kDoesNotExist = 3
- };
+ enum Type { kIsFile = 0, kIsDirectory = 1, kIsLink = 2, kDoesNotExist = 3 };
- enum Identical {
- kIdentical = 0,
- kDifferent = 1,
- kError = 2
- };
+ enum Identical { kIdentical = 0, kDifferent = 1, kError = 2 };
enum StdioHandleType {
kTerminal = 0,
@@ -105,9 +96,7 @@
// occurred the result will be set to false.
bool ReadFully(void* buffer, int64_t num_bytes);
bool WriteFully(const void* buffer, int64_t num_bytes);
- bool WriteByte(uint8_t byte) {
- return WriteFully(&byte, 1);
- }
+ bool WriteByte(uint8_t byte) { return WriteFully(&byte, 1); }
// Get the length of the file. Returns a negative value if the length cannot
// be determined (e.g. not seekable device).
@@ -217,10 +206,8 @@
static CObject* LockRequest(const CObjectArray& request);
private:
- explicit File(FileHandle* handle) :
- ReferenceCounted(),
- handle_(handle),
- weak_handle_(NULL) {}
+ explicit File(FileHandle* handle)
+ : ReferenceCounted(), handle_(handle), weak_handle_(NULL) {}
~File();
diff --git a/runtime/bin/file_android.cc b/runtime/bin/file_android.cc
index ea512ad..afe0966 100644
--- a/runtime/bin/file_android.cc
+++ b/runtime/bin/file_android.cc
@@ -7,14 +7,14 @@
#include "bin/file.h"
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
-#include <libgen.h> // NOLINT
-#include <sys/mman.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <libgen.h> // NOLINT
+#include <sys/mman.h> // NOLINT
#include <sys/sendfile.h> // NOLINT
-#include <sys/stat.h> // NOLINT
-#include <sys/types.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <sys/stat.h> // NOLINT
+#include <sys/types.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/builtin.h"
#include "bin/log.h"
@@ -27,8 +27,8 @@
class FileHandle {
public:
- explicit FileHandle(int fd) : fd_(fd) { }
- ~FileHandle() { }
+ explicit FileHandle(int fd) : fd_(fd) {}
+ ~FileHandle() {}
int fd() const { return fd_; }
void set_fd(int fd) { fd_ = fd; }
@@ -91,8 +91,7 @@
default:
return NULL;
}
- void* addr = mmap(NULL, length, prot, MAP_PRIVATE,
- handle_->fd(), position);
+ void* addr = mmap(NULL, length, prot, MAP_PRIVATE, handle_->fd(), position);
if (addr == MAP_FAILED) {
return NULL;
}
@@ -320,8 +319,7 @@
int result = 1;
while (result > 0) {
// Loop to ensure we copy everything, and not only up to 2GB.
- result = NO_RETRY_EXPECTED(
- sendfile(new_fd, old_fd, &offset, kMaxUint32));
+ result = NO_RETRY_EXPECTED(sendfile(new_fd, old_fd, &offset, kMaxUint32));
}
// From sendfile man pages:
// Applications may wish to fall back to read(2)/write(2) in the case
@@ -329,8 +327,8 @@
if ((result < 0) && ((errno == EINVAL) || (errno == ENOSYS))) {
const intptr_t kBufferSize = 8 * KB;
uint8_t buffer[kBufferSize];
- while ((result = TEMP_FAILURE_RETRY(
- read(old_fd, buffer, kBufferSize))) > 0) {
+ while ((result = TEMP_FAILURE_RETRY(read(old_fd, buffer, kBufferSize))) >
+ 0) {
int wrote = TEMP_FAILURE_RETRY(write(new_fd, buffer, result));
if (wrote != result) {
result = -1;
@@ -506,9 +504,9 @@
return File::kError;
}
return ((file_1_info.st_ino == file_2_info.st_ino) &&
- (file_1_info.st_dev == file_2_info.st_dev)) ?
- File::kIdentical :
- File::kDifferent;
+ (file_1_info.st_dev == file_2_info.st_dev))
+ ? File::kIdentical
+ : File::kDifferent;
}
} // namespace bin
diff --git a/runtime/bin/file_fuchsia.cc b/runtime/bin/file_fuchsia.cc
index ae42333..bda6113 100644
--- a/runtime/bin/file_fuchsia.cc
+++ b/runtime/bin/file_fuchsia.cc
@@ -7,13 +7,13 @@
#include "bin/file.h"
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
-#include <libgen.h> // NOLINT
-#include <sys/mman.h> // NOLINT
-#include <sys/stat.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <libgen.h> // NOLINT
+#include <sys/mman.h> // NOLINT
+#include <sys/stat.h> // NOLINT
#include <sys/types.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/builtin.h"
#include "bin/log.h"
@@ -25,8 +25,8 @@
class FileHandle {
public:
- explicit FileHandle(int fd) : fd_(fd) { }
- ~FileHandle() { }
+ explicit FileHandle(int fd) : fd_(fd) {}
+ ~FileHandle() {}
int fd() const { return fd_; }
void set_fd(int fd) { fd_ = fd; }
@@ -435,9 +435,9 @@
return File::kError;
}
return ((file_1_info.st_ino == file_2_info.st_ino) &&
- (file_1_info.st_dev == file_2_info.st_dev)) ?
- File::kIdentical :
- File::kDifferent;
+ (file_1_info.st_dev == file_2_info.st_dev))
+ ? File::kIdentical
+ : File::kDifferent;
}
} // namespace bin
diff --git a/runtime/bin/file_linux.cc b/runtime/bin/file_linux.cc
index aeba5c8..9a6dc41 100644
--- a/runtime/bin/file_linux.cc
+++ b/runtime/bin/file_linux.cc
@@ -7,14 +7,14 @@
#include "bin/file.h"
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
-#include <libgen.h> // NOLINT
-#include <sys/mman.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <libgen.h> // NOLINT
+#include <sys/mman.h> // NOLINT
#include <sys/sendfile.h> // NOLINT
-#include <sys/stat.h> // NOLINT
-#include <sys/types.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <sys/stat.h> // NOLINT
+#include <sys/types.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/builtin.h"
#include "bin/log.h"
@@ -26,8 +26,8 @@
class FileHandle {
public:
- explicit FileHandle(int fd) : fd_(fd) { }
- ~FileHandle() { }
+ explicit FileHandle(int fd) : fd_(fd) {}
+ ~FileHandle() {}
int fd() const { return fd_; }
void set_fd(int fd) { fd_ = fd; }
@@ -39,8 +39,8 @@
File::~File() {
- if (!IsClosed() &&
- handle_->fd() != STDOUT_FILENO && handle_->fd() != STDERR_FILENO) {
+ if (!IsClosed() && handle_->fd() != STDOUT_FILENO &&
+ handle_->fd() != STDERR_FILENO) {
Close();
}
delete handle_;
@@ -90,8 +90,7 @@
default:
return NULL;
}
- void* addr = mmap(NULL, length, prot, MAP_PRIVATE,
- handle_->fd(), position);
+ void* addr = mmap(NULL, length, prot, MAP_PRIVATE, handle_->fd(), position);
if (addr == MAP_FAILED) {
return NULL;
}
@@ -236,8 +235,8 @@
bool File::Create(const char* name) {
- int fd = TEMP_FAILURE_RETRY(
- open64(name, O_RDONLY | O_CREAT | O_CLOEXEC, 0666));
+ int fd =
+ TEMP_FAILURE_RETRY(open64(name, O_RDONLY | O_CREAT | O_CLOEXEC, 0666));
if (fd < 0) {
return false;
}
@@ -320,8 +319,8 @@
intptr_t result = 1;
while (result > 0) {
// Loop to ensure we copy everything, and not only up to 2GB.
- result = NO_RETRY_EXPECTED(
- sendfile64(new_fd, old_fd, &offset, kMaxUint32));
+ result =
+ NO_RETRY_EXPECTED(sendfile64(new_fd, old_fd, &offset, kMaxUint32));
}
// From sendfile man pages:
// Applications may wish to fall back to read(2)/write(2) in the case
@@ -329,8 +328,8 @@
if ((result < 0) && ((errno == EINVAL) || (errno == ENOSYS))) {
const intptr_t kBufferSize = 8 * KB;
uint8_t buffer[kBufferSize];
- while ((result = TEMP_FAILURE_RETRY(
- read(old_fd, buffer, kBufferSize))) > 0) {
+ while ((result = TEMP_FAILURE_RETRY(read(old_fd, buffer, kBufferSize))) >
+ 0) {
int wrote = TEMP_FAILURE_RETRY(write(new_fd, buffer, result));
if (wrote != result) {
result = -1;
@@ -367,7 +366,7 @@
static int64_t TimespecToMilliseconds(const struct timespec& t) {
return static_cast<int64_t>(t.tv_sec) * 1000L +
- static_cast<int64_t>(t.tv_nsec) / 1000000L;
+ static_cast<int64_t>(t.tv_nsec) / 1000000L;
}
@@ -417,8 +416,8 @@
// 0. Also the link might have changed before the readlink call.
const int kBufferSize = PATH_MAX + 1;
char target[kBufferSize];
- size_t target_size = TEMP_FAILURE_RETRY(
- readlink(pathname, target, kBufferSize));
+ size_t target_size =
+ TEMP_FAILURE_RETRY(readlink(pathname, target, kBufferSize));
if (target_size <= 0) {
return NULL;
}
@@ -518,9 +517,9 @@
return File::kError;
}
return ((file_1_info.st_ino == file_2_info.st_ino) &&
- (file_1_info.st_dev == file_2_info.st_dev)) ?
- File::kIdentical :
- File::kDifferent;
+ (file_1_info.st_dev == file_2_info.st_dev))
+ ? File::kIdentical
+ : File::kDifferent;
}
} // namespace bin
diff --git a/runtime/bin/file_macos.cc b/runtime/bin/file_macos.cc
index fe34eb7..2b32bc1 100644
--- a/runtime/bin/file_macos.cc
+++ b/runtime/bin/file_macos.cc
@@ -8,13 +8,13 @@
#include "bin/file.h"
#include <copyfile.h> // NOLINT
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
-#include <libgen.h> // NOLINT
-#include <limits.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <libgen.h> // NOLINT
+#include <limits.h> // NOLINT
#include <sys/mman.h> // NOLINT
#include <sys/stat.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/builtin.h"
#include "bin/fdutils.h"
@@ -28,8 +28,8 @@
class FileHandle {
public:
- explicit FileHandle(int fd) : fd_(fd) { }
- ~FileHandle() { }
+ explicit FileHandle(int fd) : fd_(fd) {}
+ ~FileHandle() {}
int fd() const { return fd_; }
void set_fd(int fd) { fd_ = fd; }
@@ -41,8 +41,8 @@
File::~File() {
- if (!IsClosed() &&
- handle_->fd() != STDOUT_FILENO && handle_->fd() != STDERR_FILENO) {
+ if (!IsClosed() && handle_->fd() != STDOUT_FILENO &&
+ handle_->fd() != STDERR_FILENO) {
Close();
}
delete handle_;
@@ -93,8 +93,7 @@
default:
return NULL;
}
- void* addr = mmap(NULL, length, prot, MAP_PRIVATE,
- handle_->fd(), position);
+ void* addr = mmap(NULL, length, prot, MAP_PRIVATE, handle_->fd(), position);
if (addr == MAP_FAILED) {
return NULL;
}
@@ -326,7 +325,7 @@
static int64_t TimespecToMilliseconds(const struct timespec& t) {
return static_cast<int64_t>(t.tv_sec) * 1000L +
- static_cast<int64_t>(t.tv_nsec) / 1000000L;
+ static_cast<int64_t>(t.tv_nsec) / 1000000L;
}
@@ -378,8 +377,8 @@
// target. The link might have changed before the readlink call.
const int kBufferSize = 1024;
char target[kBufferSize];
- size_t target_size = TEMP_FAILURE_RETRY(
- readlink(pathname, target, kBufferSize));
+ size_t target_size =
+ TEMP_FAILURE_RETRY(readlink(pathname, target, kBufferSize));
if (target_size <= 0) {
return NULL;
}
@@ -482,9 +481,9 @@
return File::kError;
}
return ((file_1_info.st_ino == file_2_info.st_ino) &&
- (file_1_info.st_dev == file_2_info.st_dev)) ?
- File::kIdentical :
- File::kDifferent;
+ (file_1_info.st_dev == file_2_info.st_dev))
+ ? File::kIdentical
+ : File::kDifferent;
}
} // namespace bin
diff --git a/runtime/bin/file_support.cc b/runtime/bin/file_support.cc
index 0ad5edc..41de702 100644
--- a/runtime/bin/file_support.cc
+++ b/runtime/bin/file_support.cc
@@ -50,7 +50,7 @@
if (bytes_read <= 0) {
return false;
}
- remaining -= bytes_read; // Reduce the number of remaining bytes.
+ remaining -= bytes_read; // Reduce the number of remaining bytes.
current_buffer += bytes_read; // Move the buffer forward.
}
return true;
@@ -65,7 +65,7 @@
if (bytes_written < 0) {
return false;
}
- remaining -= bytes_written; // Reduce the number of remaining bytes.
+ remaining -= bytes_written; // Reduce the number of remaining bytes.
current_buffer += bytes_written; // Move the buffer forward.
}
if (capture_stdout || capture_stderr) {
@@ -85,10 +85,8 @@
File::FileOpenMode File::DartModeToFileMode(DartFileOpenMode mode) {
- ASSERT((mode == File::kDartRead) ||
- (mode == File::kDartWrite) ||
- (mode == File::kDartAppend) ||
- (mode == File::kDartWriteOnly) ||
+ ASSERT((mode == File::kDartRead) || (mode == File::kDartWrite) ||
+ (mode == File::kDartAppend) || (mode == File::kDartWriteOnly) ||
(mode == File::kDartWriteOnlyAppend));
if (mode == File::kDartWrite) {
return File::kWriteTruncate;
diff --git a/runtime/bin/file_system_watcher.h b/runtime/bin/file_system_watcher.h
index 6bad471..8dfbbab 100644
--- a/runtime/bin/file_system_watcher.h
+++ b/runtime/bin/file_system_watcher.h
@@ -58,4 +58,3 @@
} // namespace dart
#endif // RUNTIME_BIN_FILE_SYSTEM_WATCHER_H_
-
diff --git a/runtime/bin/file_system_watcher_android.cc b/runtime/bin/file_system_watcher_android.cc
index 6843734..0cecfe2 100644
--- a/runtime/bin/file_system_watcher_android.cc
+++ b/runtime/bin/file_system_watcher_android.cc
@@ -9,7 +9,7 @@
#include "bin/file_system_watcher.h"
-#include <errno.h> // NOLINT
+#include <errno.h> // NOLINT
#include <sys/inotify.h> // NOLINT
#include "bin/fdutils.h"
@@ -127,7 +127,8 @@
Dart_ListSetAt(event, 1, Dart_NewInteger(e->cookie));
if (e->len > 0) {
Dart_ListSetAt(event, 2, Dart_NewStringFromUTF8(
- reinterpret_cast<uint8_t*>(e->name), strlen(e->name)));
+ reinterpret_cast<uint8_t*>(e->name),
+ strlen(e->name)));
} else {
Dart_ListSetAt(event, 2, Dart_Null());
}
diff --git a/runtime/bin/file_system_watcher_linux.cc b/runtime/bin/file_system_watcher_linux.cc
index 2f5179b..91c8184 100644
--- a/runtime/bin/file_system_watcher_linux.cc
+++ b/runtime/bin/file_system_watcher_linux.cc
@@ -9,7 +9,7 @@
#include "bin/file_system_watcher.h"
-#include <errno.h> // NOLINT
+#include <errno.h> // NOLINT
#include <sys/inotify.h> // NOLINT
#include "bin/fdutils.h"
@@ -128,7 +128,8 @@
Dart_ListSetAt(event, 1, Dart_NewInteger(e->cookie));
if (e->len > 0) {
Dart_ListSetAt(event, 2, Dart_NewStringFromUTF8(
- reinterpret_cast<uint8_t*>(e->name), strlen(e->name)));
+ reinterpret_cast<uint8_t*>(e->name),
+ strlen(e->name)));
} else {
Dart_ListSetAt(event, 2, Dart_Null());
}
diff --git a/runtime/bin/file_system_watcher_macos.cc b/runtime/bin/file_system_watcher_macos.cc
index 7bc0e0c..3636eb3 100644
--- a/runtime/bin/file_system_watcher_macos.cc
+++ b/runtime/bin/file_system_watcher_macos.cc
@@ -11,9 +11,9 @@
#if !TARGET_OS_IOS
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <unistd.h> // NOLINT
#include <CoreServices/CoreServices.h> // NOLINT
#include "bin/eventhandler.h"
@@ -24,9 +24,7 @@
#include "platform/signal_blocker.h"
#ifndef MAC_OS_X_VERSION_10_7
-enum {
- kFSEventStreamCreateFlagFileEvents = 0x00000010
-};
+enum { kFSEventStreamCreateFlagFileEvents = 0x00000010 };
enum {
kFSEventStreamEventFlagItemCreated = 0x00000100,
kFSEventStreamEventFlagItemRemoved = 0x00000200,
@@ -59,13 +57,17 @@
public:
class Node {
public:
- Node(FSEventsWatcher* watcher, char* base_path, int read_fd,
- int write_fd, bool recursive)
+ Node(FSEventsWatcher* watcher,
+ char* base_path,
+ int read_fd,
+ int write_fd,
+ bool recursive)
: watcher_(watcher),
ready_(false),
base_path_length_(strlen(base_path)),
- path_ref_(CFStringCreateWithCString(
- NULL, base_path, kCFStringEncodingUTF8)),
+ path_ref_(CFStringCreateWithCString(NULL,
+ base_path,
+ kCFStringEncodingUTF8)),
read_fd_(read_fd),
write_fd_(write_fd),
recursive_(recursive),
@@ -79,17 +81,15 @@
CFRelease(path_ref_);
}
- void set_ref(FSEventStreamRef ref) {
- ref_ = ref;
- }
+ void set_ref(FSEventStreamRef ref) { ref_ = ref; }
void Start() {
// Schedule StartCallback to be executed in the RunLoop.
CFRunLoopTimerContext context;
memset(&context, 0, sizeof(context));
context.info = this;
- CFRunLoopTimerRef timer = CFRunLoopTimerCreate(
- NULL, 0, 0, 0, 0, Node::StartCallback, &context);
+ CFRunLoopTimerRef timer =
+ CFRunLoopTimerCreate(NULL, 0, 0, 0, 0, Node::StartCallback, &context);
CFRunLoopAddTimer(watcher_->run_loop_, timer, kCFRunLoopCommonModes);
CFRelease(timer);
watcher_->monitor_.Enter();
@@ -109,21 +109,14 @@
CFArrayRef array = CFArrayCreate(
NULL, reinterpret_cast<const void**>(&node->path_ref_), 1, NULL);
FSEventStreamRef ref = FSEventStreamCreate(
- NULL,
- Callback,
- &context,
- array,
- kFSEventStreamEventIdSinceNow,
- 0.10,
+ NULL, Callback, &context, array, kFSEventStreamEventIdSinceNow, 0.10,
kFSEventStreamCreateFlagFileEvents);
CFRelease(array);
node->set_ref(ref);
- FSEventStreamScheduleWithRunLoop(
- node->ref_,
- node->watcher_->run_loop_,
- kCFRunLoopDefaultMode);
+ FSEventStreamScheduleWithRunLoop(node->ref_, node->watcher_->run_loop_,
+ kCFRunLoopDefaultMode);
FSEventStreamStart(node->ref_);
FSEventStreamFlushSync(node->ref_);
@@ -140,8 +133,8 @@
CFRunLoopTimerContext context;
memset(&context, 0, sizeof(context));
context.info = this;
- CFRunLoopTimerRef timer = CFRunLoopTimerCreate(
- NULL, 0, 0, 0, 0, StopCallback, &context);
+ CFRunLoopTimerRef timer =
+ CFRunLoopTimerCreate(NULL, 0, 0, 0, 0, StopCallback, &context);
CFRunLoopAddTimer(watcher_->run_loop_, timer, kCFRunLoopCommonModes);
CFRelease(timer);
watcher_->monitor_.Enter();
@@ -185,9 +178,7 @@
};
- FSEventsWatcher() : run_loop_(0) {
- Start();
- }
+ FSEventsWatcher() : run_loop_(0) { Start(); }
void Start() {
Thread::Start(Run, reinterpret_cast<uword>(this));
@@ -211,13 +202,7 @@
watcher->monitor().Exit();
CFRunLoopTimerRef timer = CFRunLoopTimerCreate(
- NULL,
- CFAbsoluteTimeGetCurrent() + 1,
- 1,
- 0,
- 0,
- TimerCallback,
- NULL);
+ NULL, CFAbsoluteTimeGetCurrent() + 1, 1, 0, 0, TimerCallback, NULL);
CFRunLoopAddTimer(watcher->run_loop_, timer, kCFRunLoopCommonModes);
CFRelease(timer);
@@ -235,8 +220,8 @@
CFRunLoopTimerContext context;
memset(&context, 0, sizeof(context));
context.info = this;
- CFRunLoopTimerRef timer = CFRunLoopTimerCreate(
- NULL, 0, 0, 0, 0, StopCallback, &context);
+ CFRunLoopTimerRef timer =
+ CFRunLoopTimerCreate(NULL, 0, 0, 0, 0, StopCallback, &context);
CFRunLoopAddTimer(run_loop_, timer, kCFRunLoopCommonModes);
CFRelease(timer);
monitor_.Enter();
@@ -248,14 +233,11 @@
static void StopCallback(CFRunLoopTimerRef timer, void* info) {
FSEventsWatcher* watcher = reinterpret_cast<FSEventsWatcher*>(info);
- ASSERT(Thread::Compare(watcher->threadId_,
- Thread::GetCurrentThreadId()));
+ ASSERT(Thread::Compare(watcher->threadId_, Thread::GetCurrentThreadId()));
CFRunLoopStop(watcher->run_loop_);
}
- ~FSEventsWatcher() {
- Stop();
- }
+ ~FSEventsWatcher() { Stop(); }
Monitor& monitor() { return monitor_; }
@@ -293,7 +275,7 @@
return;
}
for (size_t i = 0; i < num_events; i++) {
- char *path = reinterpret_cast<char**>(event_paths)[i];
+ char* path = reinterpret_cast<char**>(event_paths)[i];
FSEvent event;
event.data.exists = File::GetType(path, false) != File::kDoesNotExist;
path += node->base_path_length();
@@ -318,7 +300,7 @@
};
-#define kCFCoreFoundationVersionNumber10_7 635.00
+#define kCFCoreFoundationVersionNumber10_7 635.00
bool FileSystemWatcher::IsSupported() {
return kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber10_7;
}
@@ -402,8 +384,9 @@
}
Dart_ListSetAt(event, 0, Dart_NewInteger(mask));
Dart_ListSetAt(event, 1, Dart_NewInteger(1));
- Dart_ListSetAt(event, 2, Dart_NewStringFromUTF8(
- reinterpret_cast<uint8_t*>(e.data.path), path_len));
+ Dart_ListSetAt(event, 2,
+ Dart_NewStringFromUTF8(
+ reinterpret_cast<uint8_t*>(e.data.path), path_len));
Dart_ListSetAt(event, 3, Dart_NewBoolean(true));
Dart_ListSetAt(event, 4, Dart_NewInteger(path_id));
Dart_ListSetAt(events, i, event);
@@ -435,8 +418,7 @@
}
-void FileSystemWatcher::UnwatchPath(intptr_t id, intptr_t path_id) {
-}
+void FileSystemWatcher::UnwatchPath(intptr_t id, intptr_t path_id) {}
intptr_t FileSystemWatcher::Init() {
@@ -444,8 +426,7 @@
}
-void FileSystemWatcher::Close(intptr_t id) {
-}
+void FileSystemWatcher::Close(intptr_t id) {}
intptr_t FileSystemWatcher::WatchPath(intptr_t id,
diff --git a/runtime/bin/file_system_watcher_unsupported.cc b/runtime/bin/file_system_watcher_unsupported.cc
index 7803215..82c6c70 100644
--- a/runtime/bin/file_system_watcher_unsupported.cc
+++ b/runtime/bin/file_system_watcher_unsupported.cc
@@ -13,43 +13,43 @@
void FUNCTION_NAME(FileSystemWatcher_IsSupported)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "FileSystemWatcher is not supported on this platform"));
+ "FileSystemWatcher is not supported on this platform"));
}
void FUNCTION_NAME(FileSystemWatcher_InitWatcher)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "FileSystemWatcher is not supported on this platform"));
+ "FileSystemWatcher is not supported on this platform"));
}
void FUNCTION_NAME(FileSystemWatcher_CloseWatcher)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "FileSystemWatcher is not supported on this platform"));
+ "FileSystemWatcher is not supported on this platform"));
}
void FUNCTION_NAME(FileSystemWatcher_WatchPath)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "FileSystemWatcher is not supported on this platform"));
+ "FileSystemWatcher is not supported on this platform"));
}
void FUNCTION_NAME(FileSystemWatcher_UnwatchPath)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "FileSystemWatcher is not supported on this platform"));
+ "FileSystemWatcher is not supported on this platform"));
}
void FUNCTION_NAME(FileSystemWatcher_ReadEvents)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "FileSystemWatcher is not supported on this platform"));
+ "FileSystemWatcher is not supported on this platform"));
}
void FUNCTION_NAME(FileSystemWatcher_GetSocketId)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "FileSystemWatcher is not supported on this platform"));
+ "FileSystemWatcher is not supported on this platform"));
}
} // namespace bin
diff --git a/runtime/bin/file_system_watcher_win.cc b/runtime/bin/file_system_watcher_win.cc
index ced2cef..16a49a0 100644
--- a/runtime/bin/file_system_watcher_win.cc
+++ b/runtime/bin/file_system_watcher_win.cc
@@ -41,15 +41,10 @@
bool recursive) {
USE(id);
Utf8ToWideScope name(path);
- HANDLE dir = CreateFileW(name.wide(),
- FILE_LIST_DIRECTORY,
- FILE_SHARE_READ |
- FILE_SHARE_WRITE |
- FILE_SHARE_DELETE,
- NULL,
- OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
- NULL);
+ HANDLE dir = CreateFileW(
+ name.wide(), FILE_LIST_DIRECTORY,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
+ OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL);
if (dir == INVALID_HANDLE_VALUE) {
return -1;
@@ -57,8 +52,7 @@
int list_events = 0;
if ((events & (kCreate | kMove | kDelete)) != 0) {
- list_events |= FILE_NOTIFY_CHANGE_FILE_NAME |
- FILE_NOTIFY_CHANGE_DIR_NAME;
+ list_events |= FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME;
}
if ((events & kModifyContent) != 0) {
list_events |= FILE_NOTIFY_CHANGE_LAST_WRITE;
@@ -124,7 +118,8 @@
// Move events come in pairs. Just 'enable' by default.
Dart_ListSetAt(event, 1, Dart_NewInteger(1));
Dart_ListSetAt(event, 2, Dart_NewStringFromUTF16(
- reinterpret_cast<uint16_t*>(e->FileName), e->FileNameLength / 2));
+ reinterpret_cast<uint16_t*>(e->FileName),
+ e->FileNameLength / 2));
Dart_ListSetAt(event, 3, Dart_NewBoolean(true));
Dart_ListSetAt(event, 4, Dart_NewInteger(path_id));
Dart_ListSetAt(events, i, event);
diff --git a/runtime/bin/file_unsupported.cc b/runtime/bin/file_unsupported.cc
index 55a88d0..88e85c6 100644
--- a/runtime/bin/file_unsupported.cc
+++ b/runtime/bin/file_unsupported.cc
@@ -13,194 +13,194 @@
void FUNCTION_NAME(File_GetPointer)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_SetPointer)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Open)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Exists)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Close)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_ReadByte)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_WriteByte)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Read)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_ReadInto)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_WriteFrom)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Position)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_SetPosition)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Truncate)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Length)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_LengthFromPath)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_LastModified)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Flush)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Lock)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Create)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_CreateLink)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_LinkTarget)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Delete)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_DeleteLink)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Rename)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_RenameLink)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Copy)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_ResolveSymbolicLinks)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_OpenStdio)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_GetStdioHandleType)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_GetType)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_Stat)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
void FUNCTION_NAME(File_AreIdentical)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "File is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("File is not supported on this platform"));
}
} // namespace bin
diff --git a/runtime/bin/file_win.cc b/runtime/bin/file_win.cc
index fc72a78..79272d3 100644
--- a/runtime/bin/file_win.cc
+++ b/runtime/bin/file_win.cc
@@ -7,10 +7,10 @@
#include "bin/file.h"
-#include <fcntl.h> // NOLINT
-#include <io.h> // NOLINT
-#include <stdio.h> // NOLINT
-#include <string.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <io.h> // NOLINT
+#include <stdio.h> // NOLINT
+#include <string.h> // NOLINT
#include <sys/stat.h> // NOLINT
#include <WinIoCtl.h> // NOLINT
@@ -25,8 +25,8 @@
class FileHandle {
public:
- explicit FileHandle(int fd) : fd_(fd) { }
- ~FileHandle() { }
+ explicit FileHandle(int fd) : fd_(fd) {}
+ ~FileHandle() {}
int fd() const { return fd_; }
void set_fd(int fd) { fd_ = fd; }
@@ -38,8 +38,8 @@
File::~File() {
- if (!IsClosed() &&
- handle_->fd() != _fileno(stdout) && handle_->fd() != _fileno(stderr)) {
+ if (!IsClosed() && handle_->fd() != _fileno(stdout) &&
+ handle_->fd() != _fileno(stderr)) {
Close();
}
delete handle_;
@@ -184,8 +184,7 @@
(lock == File::kLockBlockingExclusive)) {
flags |= LOCKFILE_EXCLUSIVE_LOCK;
}
- rc = LockFileEx(handle, flags, 0,
- length_low, length_high, &overlapped);
+ rc = LockFileEx(handle, flags, 0, length_low, length_high, &overlapped);
break;
}
default:
@@ -280,32 +279,32 @@
// This structure is needed for creating and reading Junctions.
typedef struct _REPARSE_DATA_BUFFER {
- ULONG ReparseTag;
- USHORT ReparseDataLength;
- USHORT Reserved;
+ ULONG ReparseTag;
+ USHORT ReparseDataLength;
+ USHORT Reserved;
- union {
- struct {
- USHORT SubstituteNameOffset;
- USHORT SubstituteNameLength;
- USHORT PrintNameOffset;
- USHORT PrintNameLength;
- ULONG Flags;
- WCHAR PathBuffer[1];
- } SymbolicLinkReparseBuffer;
+ union {
+ struct {
+ USHORT SubstituteNameOffset;
+ USHORT SubstituteNameLength;
+ USHORT PrintNameOffset;
+ USHORT PrintNameLength;
+ ULONG Flags;
+ WCHAR PathBuffer[1];
+ } SymbolicLinkReparseBuffer;
- struct {
- USHORT SubstituteNameOffset;
- USHORT SubstituteNameLength;
- USHORT PrintNameOffset;
- USHORT PrintNameLength;
- WCHAR PathBuffer[1];
- } MountPointReparseBuffer;
+ struct {
+ USHORT SubstituteNameOffset;
+ USHORT SubstituteNameLength;
+ USHORT PrintNameOffset;
+ USHORT PrintNameLength;
+ WCHAR PathBuffer[1];
+ } MountPointReparseBuffer;
- struct {
- UCHAR DataBuffer[1];
- } GenericReparseBuffer;
- };
+ struct {
+ UCHAR DataBuffer[1];
+ } GenericReparseBuffer;
+ };
} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
@@ -324,12 +323,9 @@
}
HANDLE dir_handle = CreateFileW(
- name.wide(),
- GENERIC_READ | GENERIC_WRITE,
- FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
- NULL,
- OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
+ name.wide(), GENERIC_READ | GENERIC_WRITE,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
+ OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
NULL);
if (dir_handle == INVALID_HANDLE_VALUE) {
return false;
@@ -363,14 +359,9 @@
(target_len + 1) * 2 * sizeof WCHAR + kMountPointHeaderSize;
DWORD dummy_received_bytes;
int result = DeviceIoControl(
- dir_handle,
- FSCTL_SET_REPARSE_POINT,
- reparse_data_buffer,
- reparse_data_buffer->ReparseDataLength + kReparseDataHeaderSize,
- NULL,
- 0,
- &dummy_received_bytes,
- NULL);
+ dir_handle, FSCTL_SET_REPARSE_POINT, reparse_data_buffer,
+ reparse_data_buffer->ReparseDataLength + kReparseDataHeaderSize, NULL, 0,
+ &dummy_received_bytes, NULL);
free(reparse_data_buffer);
if (CloseHandle(dir_handle) == 0) {
return false;
@@ -438,12 +429,8 @@
if (type == kIsFile) {
Utf8ToWideScope system_old_path(old_path);
Utf8ToWideScope system_new_path(new_path);
- bool success = CopyFileExW(system_old_path.wide(),
- system_new_path.wide(),
- NULL,
- NULL,
- NULL,
- 0) != 0;
+ bool success = CopyFileExW(system_old_path.wide(), system_new_path.wide(),
+ NULL, NULL, NULL, 0) != 0;
return success;
} else {
SetLastError(ERROR_FILE_NOT_FOUND);
@@ -466,12 +453,9 @@
const char* File::LinkTarget(const char* pathname) {
const wchar_t* name = StringUtilsWin::Utf8ToWide(pathname);
HANDLE dir_handle = CreateFileW(
- name,
- GENERIC_READ,
- FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
- NULL,
- OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
+ name, GENERIC_READ,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
+ OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
NULL);
if (dir_handle == INVALID_HANDLE_VALUE) {
return NULL;
@@ -479,18 +463,11 @@
int buffer_size =
sizeof REPARSE_DATA_BUFFER + 2 * (MAX_PATH + 1) * sizeof WCHAR;
- REPARSE_DATA_BUFFER* buffer = reinterpret_cast<REPARSE_DATA_BUFFER*>(
- Dart_ScopeAllocate(buffer_size));
+ REPARSE_DATA_BUFFER* buffer =
+ reinterpret_cast<REPARSE_DATA_BUFFER*>(Dart_ScopeAllocate(buffer_size));
DWORD received_bytes; // Value is not used.
- int result = DeviceIoControl(
- dir_handle,
- FSCTL_GET_REPARSE_POINT,
- NULL,
- 0,
- buffer,
- buffer_size,
- &received_bytes,
- NULL);
+ int result = DeviceIoControl(dir_handle, FSCTL_GET_REPARSE_POINT, NULL, 0,
+ buffer, buffer_size, &received_bytes, NULL);
if (result == 0) {
DWORD error = GetLastError();
CloseHandle(dir_handle);
@@ -525,23 +502,11 @@
target += 4;
target_length -= 4;
}
- int utf8_length = WideCharToMultiByte(CP_UTF8,
- 0,
- target,
- target_length,
- NULL,
- 0,
- NULL,
- NULL);
+ int utf8_length = WideCharToMultiByte(CP_UTF8, 0, target, target_length, NULL,
+ 0, NULL, NULL);
char* utf8_target = DartUtils::ScopedCString(utf8_length + 1);
- if (0 == WideCharToMultiByte(CP_UTF8,
- 0,
- target,
- target_length,
- utf8_target,
- utf8_length,
- NULL,
- NULL)) {
+ if (0 == WideCharToMultiByte(CP_UTF8, 0, target, target_length, utf8_target,
+ utf8_length, NULL, NULL)) {
return NULL;
}
utf8_target[utf8_length] = '\0';
@@ -585,30 +550,22 @@
if (pathname == NULL) {
return false;
}
- return ((strlen(pathname) > 2) &&
- (pathname[1] == ':') &&
- ((pathname[2] == '\\') || (pathname[2] == '/')));
+ return ((strlen(pathname) > 2) && (pathname[1] == ':') &&
+ ((pathname[2] == '\\') || (pathname[2] == '/')));
}
const char* File::GetCanonicalPath(const char* pathname) {
Utf8ToWideScope system_name(pathname);
- HANDLE file_handle = CreateFileW(
- system_name.wide(),
- 0,
- FILE_SHARE_READ,
- NULL,
- OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS,
- NULL);
+ HANDLE file_handle =
+ CreateFileW(system_name.wide(), 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
+ FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (file_handle == INVALID_HANDLE_VALUE) {
return NULL;
}
wchar_t dummy_buffer[1];
- int required_size = GetFinalPathNameByHandle(file_handle,
- dummy_buffer,
- 0,
- VOLUME_NAME_DOS);
+ int required_size =
+ GetFinalPathNameByHandle(file_handle, dummy_buffer, 0, VOLUME_NAME_DOS);
if (required_size == 0) {
DWORD error = GetLastError();
CloseHandle(file_handle);
@@ -618,15 +575,12 @@
wchar_t* path;
path = reinterpret_cast<wchar_t*>(
Dart_ScopeAllocate(required_size * sizeof(*path)));
- int result_size = GetFinalPathNameByHandle(file_handle,
- path,
- required_size,
+ int result_size = GetFinalPathNameByHandle(file_handle, path, required_size,
VOLUME_NAME_DOS);
ASSERT(result_size <= required_size - 1);
// Remove leading \\?\ if possible, unless input used it.
char* result;
- if ((result_size < MAX_PATH - 1 + 4) &&
- (result_size > 4) &&
+ if ((result_size < MAX_PATH - 1 + 4) && (result_size > 4) &&
(wcsncmp(path, L"\\\\?\\", 4) == 0) &&
(wcsncmp(system_name.wide(), L"\\\\?\\", 4) != 0)) {
result = StringUtilsWin::WideToUtf8(path + 4);
@@ -666,14 +620,10 @@
result = kDoesNotExist;
} else if ((attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
if (follow_links) {
- HANDLE dir_handle = CreateFileW(
- name.wide(),
- 0,
- FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
- NULL,
- OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS,
- NULL);
+ HANDLE dir_handle =
+ CreateFileW(name.wide(), 0,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (dir_handle == INVALID_HANDLE_VALUE) {
result = File::kIsLink;
} else {
@@ -692,17 +642,14 @@
File::Identical File::AreIdentical(const char* file_1, const char* file_2) {
BY_HANDLE_FILE_INFORMATION file_info[2];
- const char* file_names[2] = { file_1, file_2 };
+ const char* file_names[2] = {file_1, file_2};
for (int i = 0; i < 2; ++i) {
Utf8ToWideScope wide_name(file_names[i]);
HANDLE file_handle = CreateFileW(
- wide_name.wide(),
- 0,
- FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
- NULL,
+ wide_name.wide(), 0,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
- NULL);
+ FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
if (file_handle == INVALID_HANDLE_VALUE) {
return File::kError;
}
@@ -718,7 +665,7 @@
}
}
if ((file_info[0].dwVolumeSerialNumber ==
- file_info[1].dwVolumeSerialNumber) &&
+ file_info[1].dwVolumeSerialNumber) &&
(file_info[0].nFileIndexHigh == file_info[1].nFileIndexHigh) &&
(file_info[0].nFileIndexLow == file_info[1].nFileIndexLow)) {
return kIdentical;
diff --git a/runtime/bin/filter.cc b/runtime/bin/filter.cc
index 60887ef..6665979 100644
--- a/runtime/bin/filter.cc
+++ b/runtime/bin/filter.cc
@@ -52,8 +52,8 @@
return Dart_NewApiError("Could not allocate new dictionary");
}
- err = Dart_TypedDataAcquireData(
- dictionary_obj, &type, reinterpret_cast<void**>(&src), &size);
+ err = Dart_TypedDataAcquireData(dictionary_obj, &type,
+ reinterpret_cast<void**>(&src), &size);
if (!Dart_IsError(err)) {
memmove(result, src, size);
Dart_TypedDataReleaseData(dictionary_obj);
@@ -99,13 +99,13 @@
static_cast<int32_t>(window_bits), dictionary, dictionary_length, raw);
if (filter == NULL) {
delete[] dictionary;
- Dart_PropagateError(Dart_NewApiError(
- "Could not allocate ZLibInflateFilter"));
+ Dart_PropagateError(
+ Dart_NewApiError("Could not allocate ZLibInflateFilter"));
}
if (!filter->Init()) {
delete filter;
- Dart_ThrowException(DartUtils::NewInternalError(
- "Failed to create ZLibInflateFilter"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Failed to create ZLibInflateFilter"));
}
err = Filter::SetFilterAndCreateFinalizer(
filter_obj, filter, sizeof(*filter) + dictionary_length);
@@ -121,8 +121,8 @@
Dart_Handle gzip_obj = Dart_GetNativeArgument(args, 1);
bool gzip = DartUtils::GetBooleanValue(gzip_obj);
Dart_Handle level_obj = Dart_GetNativeArgument(args, 2);
- int64_t level = DartUtils::GetInt64ValueCheckRange(level_obj, kMinInt32,
- kMaxInt32);
+ int64_t level =
+ DartUtils::GetInt64ValueCheckRange(level_obj, kMinInt32, kMaxInt32);
Dart_Handle window_bits_obj = Dart_GetNativeArgument(args, 3);
int64_t window_bits = DartUtils::GetIntegerValue(window_bits_obj);
Dart_Handle mLevel_obj = Dart_GetNativeArgument(args, 4);
@@ -151,21 +151,18 @@
}
ZLibDeflateFilter* filter = new ZLibDeflateFilter(
- gzip,
- static_cast<int32_t>(level),
- static_cast<int32_t>(window_bits),
- static_cast<int32_t>(mem_level),
- static_cast<int32_t>(strategy),
+ gzip, static_cast<int32_t>(level), static_cast<int32_t>(window_bits),
+ static_cast<int32_t>(mem_level), static_cast<int32_t>(strategy),
dictionary, dictionary_length, raw);
if (filter == NULL) {
delete[] dictionary;
- Dart_PropagateError(Dart_NewApiError(
- "Could not allocate ZLibDeflateFilter"));
+ Dart_PropagateError(
+ Dart_NewApiError("Could not allocate ZLibDeflateFilter"));
}
if (!filter->Init()) {
delete filter;
- Dart_ThrowException(DartUtils::NewInternalError(
- "Failed to create ZLibDeflateFilter"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Failed to create ZLibDeflateFilter"));
}
Dart_Handle result = Filter::SetFilterAndCreateFinalizer(
filter_obj, filter, sizeof(*filter) + dictionary_length);
@@ -247,13 +244,10 @@
Dart_PropagateError(err);
}
- intptr_t read = filter->Processed(filter->processed_buffer(),
- filter->processed_buffer_size(),
- flush,
- end);
+ intptr_t read = filter->Processed(
+ filter->processed_buffer(), filter->processed_buffer_size(), flush, end);
if (read < 0) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Filter error, bad data"));
+ Dart_ThrowException(DartUtils::NewInternalError("Filter error, bad data"));
} else if (read == 0) {
Dart_SetReturnValue(args, Dart_Null());
} else {
@@ -265,10 +259,9 @@
}
-static void DeleteFilter(
- void* isolate_data,
- Dart_WeakPersistentHandle handle,
- void* filter_pointer) {
+static void DeleteFilter(void* isolate_data,
+ Dart_WeakPersistentHandle handle,
+ void* filter_pointer) {
Filter* filter = reinterpret_cast<Filter*>(filter_pointer);
delete filter;
}
@@ -277,17 +270,14 @@
Dart_Handle Filter::SetFilterAndCreateFinalizer(Dart_Handle filter,
Filter* filter_pointer,
intptr_t size) {
- Dart_Handle err = Dart_SetNativeInstanceField(
- filter,
- kFilterPointerNativeField,
- reinterpret_cast<intptr_t>(filter_pointer));
+ Dart_Handle err =
+ Dart_SetNativeInstanceField(filter, kFilterPointerNativeField,
+ reinterpret_cast<intptr_t>(filter_pointer));
if (Dart_IsError(err)) {
return err;
}
- Dart_NewWeakPersistentHandle(filter,
- reinterpret_cast<void*>(filter_pointer),
- size,
- DeleteFilter);
+ Dart_NewWeakPersistentHandle(filter, reinterpret_cast<void*>(filter_pointer),
+ size, DeleteFilter);
return err;
}
@@ -295,8 +285,7 @@
Dart_Handle Filter::GetFilterNativeField(Dart_Handle filter,
Filter** filter_pointer) {
return Dart_GetNativeInstanceField(
- filter,
- kFilterPointerNativeField,
+ filter, kFilterPointerNativeField,
reinterpret_cast<intptr_t*>(filter_pointer));
}
@@ -355,8 +344,8 @@
stream_.avail_out = length;
stream_.next_out = buffer;
bool error = false;
- switch (deflate(&stream_,
- end ? Z_FINISH : flush ? Z_SYNC_FLUSH : Z_NO_FLUSH)) {
+ switch (
+ deflate(&stream_, end ? Z_FINISH : flush ? Z_SYNC_FLUSH : Z_NO_FLUSH)) {
case Z_STREAM_END:
case Z_BUF_ERROR:
case Z_OK: {
@@ -369,7 +358,7 @@
default:
case Z_STREAM_ERROR:
- error = true;
+ error = true;
}
delete[] current_buffer_;
@@ -389,9 +378,8 @@
bool ZLibInflateFilter::Init() {
- int window_bits = raw_ ?
- -window_bits_ :
- window_bits_ | kZLibFlagAcceptAnyHeader;
+ int window_bits =
+ raw_ ? -window_bits_ : window_bits_ | kZLibFlagAcceptAnyHeader;
stream_.next_in = Z_NULL;
stream_.avail_in = 0;
@@ -426,7 +414,7 @@
bool error = false;
int v;
switch (v = inflate(&stream_,
- end ? Z_FINISH : flush ? Z_SYNC_FLUSH : Z_NO_FLUSH)) {
+ end ? Z_FINISH : flush ? Z_SYNC_FLUSH : Z_NO_FLUSH)) {
case Z_STREAM_END:
case Z_BUF_ERROR:
case Z_OK: {
@@ -441,8 +429,8 @@
if (dictionary_ == NULL) {
error = true;
} else {
- int result = inflateSetDictionary(&stream_, dictionary_,
- dictionary_length_);
+ int result =
+ inflateSetDictionary(&stream_, dictionary_, dictionary_length_);
delete[] dictionary_;
dictionary_ = NULL;
error = result != Z_OK;
diff --git a/runtime/bin/filter.h b/runtime/bin/filter.h
index 54693c0..9239d56 100644
--- a/runtime/bin/filter.h
+++ b/runtime/bin/filter.h
@@ -29,7 +29,9 @@
* a delete[] call.
*/
virtual bool Process(uint8_t* data, intptr_t length) = 0;
- virtual intptr_t Processed(uint8_t* buffer, intptr_t length, bool finish,
+ virtual intptr_t Processed(uint8_t* buffer,
+ intptr_t length,
+ bool finish,
bool end) = 0;
static Dart_Handle SetFilterAndCreateFinalizer(Dart_Handle filter,
@@ -56,18 +58,30 @@
class ZLibDeflateFilter : public Filter {
public:
- ZLibDeflateFilter(bool gzip, int32_t level, int32_t window_bits,
- int32_t mem_level, int32_t strategy,
- uint8_t* dictionary, intptr_t dictionary_length, bool raw)
- : gzip_(gzip), level_(level), window_bits_(window_bits),
- mem_level_(mem_level), strategy_(strategy), dictionary_(dictionary),
- dictionary_length_(dictionary_length), raw_(raw), current_buffer_(NULL)
- {}
+ ZLibDeflateFilter(bool gzip,
+ int32_t level,
+ int32_t window_bits,
+ int32_t mem_level,
+ int32_t strategy,
+ uint8_t* dictionary,
+ intptr_t dictionary_length,
+ bool raw)
+ : gzip_(gzip),
+ level_(level),
+ window_bits_(window_bits),
+ mem_level_(mem_level),
+ strategy_(strategy),
+ dictionary_(dictionary),
+ dictionary_length_(dictionary_length),
+ raw_(raw),
+ current_buffer_(NULL) {}
virtual ~ZLibDeflateFilter();
virtual bool Init();
virtual bool Process(uint8_t* data, intptr_t length);
- virtual intptr_t Processed(uint8_t* buffer, intptr_t length, bool finish,
+ virtual intptr_t Processed(uint8_t* buffer,
+ intptr_t length,
+ bool finish,
bool end);
private:
@@ -87,16 +101,22 @@
class ZLibInflateFilter : public Filter {
public:
- ZLibInflateFilter(int32_t window_bits, uint8_t* dictionary,
- intptr_t dictionary_length, bool raw)
- : window_bits_(window_bits), dictionary_(dictionary),
- dictionary_length_(dictionary_length), raw_(raw), current_buffer_(NULL)
- {}
+ ZLibInflateFilter(int32_t window_bits,
+ uint8_t* dictionary,
+ intptr_t dictionary_length,
+ bool raw)
+ : window_bits_(window_bits),
+ dictionary_(dictionary),
+ dictionary_length_(dictionary_length),
+ raw_(raw),
+ current_buffer_(NULL) {}
virtual ~ZLibInflateFilter();
virtual bool Init();
virtual bool Process(uint8_t* data, intptr_t length);
- virtual intptr_t Processed(uint8_t* buffer, intptr_t length, bool finish,
+ virtual intptr_t Processed(uint8_t* buffer,
+ intptr_t length,
+ bool finish,
bool end);
private:
diff --git a/runtime/bin/filter_unsupported.cc b/runtime/bin/filter_unsupported.cc
index 37d7b6f..d330393 100644
--- a/runtime/bin/filter_unsupported.cc
+++ b/runtime/bin/filter_unsupported.cc
@@ -13,25 +13,25 @@
void FUNCTION_NAME(Filter_CreateZLibInflate)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "ZLibInflater and Deflater not supported on this platform"));
+ "ZLibInflater and Deflater not supported on this platform"));
}
void FUNCTION_NAME(Filter_CreateZLibDeflate)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "ZLibInflater and Deflater not supported on this platform"));
+ "ZLibInflater and Deflater not supported on this platform"));
}
void FUNCTION_NAME(Filter_Process)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "ZLibInflater and Deflater not supported on this platform"));
+ "ZLibInflater and Deflater not supported on this platform"));
}
void FUNCTION_NAME(Filter_Processed)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "ZLibInflater and Deflater not supported on this platform"));
+ "ZLibInflater and Deflater not supported on this platform"));
}
} // namespace bin
diff --git a/runtime/bin/gen_snapshot.cc b/runtime/bin/gen_snapshot.cc
index 05452ae..17acc09 100644
--- a/runtime/bin/gen_snapshot.cc
+++ b/runtime/bin/gen_snapshot.cc
@@ -140,8 +140,8 @@
name[name_len] = '\0';
value = strdup(equals_pos + 1);
}
- HashMap::Entry* entry = environment->Lookup(
- GetHashmapKeyFromString(name), HashMap::StringHash(name), true);
+ HashMap::Entry* entry = environment->Lookup(GetHashmapKeyFromString(name),
+ HashMap::StringHash(name), true);
ASSERT(entry != NULL); // Lookup adds an entry if key not found.
entry->value = value;
return true;
@@ -162,10 +162,9 @@
name_chars[utf8_len] = '\0';
const char* value = NULL;
if (environment != NULL) {
- HashMap::Entry* entry = environment->Lookup(
- GetHashmapKeyFromString(name_chars),
- HashMap::StringHash(name_chars),
- false);
+ HashMap::Entry* entry =
+ environment->Lookup(GetHashmapKeyFromString(name_chars),
+ HashMap::StringHash(name_chars), false);
if (entry != NULL) {
value = reinterpret_cast<char*>(entry->value);
}
@@ -180,7 +179,6 @@
}
-
static const char* ProcessOption(const char* option, const char* name) {
const intptr_t length = strlen(name);
if (strncmp(option, name, length) == 0) {
@@ -311,10 +309,8 @@
ProcessInstructionsBlobOption(argv[i]) ||
ProcessRodataBlobOption(argv[i]) ||
ProcessEmbedderEntryPointsManifestOption(argv[i]) ||
- ProcessURLmappingOption(argv[i]) ||
- ProcessPackageRootOption(argv[i]) ||
- ProcessPackagesOption(argv[i]) ||
- ProcessEnvironmentOption(argv[i])) {
+ ProcessURLmappingOption(argv[i]) || ProcessPackageRootOption(argv[i]) ||
+ ProcessPackagesOption(argv[i]) || ProcessEnvironmentOption(argv[i])) {
i += 1;
continue;
}
@@ -333,8 +329,9 @@
// Verify consistency of arguments.
if ((commandline_package_root != NULL) &&
(commandline_packages_file != NULL)) {
- Log::PrintErr("Specifying both a packages directory and a packages "
- "file is invalid.\n");
+ Log::PrintErr(
+ "Specifying both a packages directory and a packages "
+ "file is invalid.\n");
return -1;
}
@@ -349,25 +346,24 @@
}
bool precompiled_as_assembly = assembly_filename != NULL;
- bool precompiled_as_blobs = (instructions_blob_filename != NULL) ||
- (rodata_blob_filename != NULL);
+ bool precompiled_as_blobs =
+ (instructions_blob_filename != NULL) || (rodata_blob_filename != NULL);
if (precompiled_as_assembly && precompiled_as_blobs) {
Log::PrintErr(
- "Cannot request a precompiled snapshot simultaneously as "
- "assembly (--assembly=<output.file>) and as blobs "
- "(--instructions-blob=<output.file> and "
- "--rodata-blob=<output.file>)\n\n");
+ "Cannot request a precompiled snapshot simultaneously as "
+ "assembly (--assembly=<output.file>) and as blobs "
+ "(--instructions-blob=<output.file> and "
+ "--rodata-blob=<output.file>)\n\n");
return -1;
}
if ((instructions_blob_filename != NULL) != (rodata_blob_filename != NULL)) {
Log::PrintErr(
- "Requesting a precompiled snapshot as blobs requires both "
- "(--instructions-blob=<output.file> and "
- "--rodata-blob=<output.file>)\n\n");
+ "Requesting a precompiled snapshot as blobs requires both "
+ "(--instructions-blob=<output.file> and "
+ "--rodata-blob=<output.file>)\n\n");
return -1;
}
- if (IsSnapshottingForPrecompilation() &&
- (entry_points_files->count() == 0)) {
+ if (IsSnapshottingForPrecompilation() && (entry_points_files->count() == 0)) {
Log::PrintErr(
"Specifying an instructions snapshot filename indicates precompilation"
". But no embedder entry points manifest was specified.\n\n");
@@ -434,9 +430,8 @@
UriResolverIsolateScope scope;
Dart_Handle resolved_uri = Dart_NewStringFromCString(uri_string);
- Dart_Handle result = Loader::LoadUrlContents(resolved_uri,
- &payload,
- &payload_length);
+ Dart_Handle result =
+ Loader::LoadUrlContents(resolved_uri, &payload, &payload_length);
if (Dart_IsError(result)) {
failed = true;
result_string = strdup(Dart_GetError(result));
@@ -475,8 +470,8 @@
}
}
- Dart_Handle result = failed ? Dart_NewApiError(result_string) :
- DartUtils::NewString(result_string);
+ Dart_Handle result = failed ? Dart_NewApiError(result_string)
+ : DartUtils::NewString(result_string);
free(result_string);
return result;
}
@@ -491,7 +486,7 @@
}
// Now load the contents of the specified uri.
const char* resolved_uri_string = DartUtils::GetStringValue(resolved_uri);
- Dart_Handle source = LoadUrlContents(resolved_uri_string);
+ Dart_Handle source = LoadUrlContents(resolved_uri_string);
if (Dart_IsError(source)) {
return source;
@@ -526,8 +521,8 @@
return Dart_NewApiError("accessing library url failed");
}
const char* library_url_string = DartUtils::GetStringValue(library_url);
- const char* mapped_library_url_string = DartUtils::MapLibraryUrl(
- library_url_string);
+ const char* mapped_library_url_string =
+ DartUtils::MapLibraryUrl(library_url_string);
if (mapped_library_url_string != NULL) {
library_url = ResolveUriInWorkingDirectory(mapped_library_url_string);
library_url_string = DartUtils::GetStringValue(library_url);
@@ -565,7 +560,8 @@
// Special case for parting sources of a builtin library.
if (tag == Dart_kSourceTag) {
return Dart_LoadSource(library, url, Dart_Null(),
- Builtin::PartSource(libraryBuiltinId, url_string), 0, 0);
+ Builtin::PartSource(libraryBuiltinId, url_string),
+ 0, 0);
}
ASSERT(tag == Dart_kImportTag);
return DartUtils::NewError("Unable to import '%s' ", url_string);
@@ -580,7 +576,7 @@
}
}
const char* resolved_uri_string = DartUtils::GetStringValue(resolved_url);
- Dart_Handle source = LoadUrlContents(resolved_uri_string);
+ Dart_Handle source = LoadUrlContents(resolved_uri_string);
if (Dart_IsError(source)) {
return source;
}
@@ -608,6 +604,7 @@
}
+// clang-format off
static void PrintUsage() {
Log::PrintErr(
"Usage: \n"
@@ -669,6 +666,7 @@
" points into Dart code from the C API. \n"
"\n");
}
+// clang-format on
static void VerifyLoaded(Dart_Handle library) {
@@ -698,7 +696,7 @@
static const uint8_t* StubNativeSymbol(Dart_NativeFunction nf) {
- return reinterpret_cast<const uint8_t *>(StubNativeFunctionName);
+ return reinterpret_cast<const uint8_t*>(StubNativeFunctionName);
}
@@ -715,20 +713,15 @@
static const uint32_t kLoadBufferMaxSize = 128;
char* load_buffer =
reinterpret_cast<char*>(calloc(kLoadBufferMaxSize, sizeof(char)));
- snprintf(load_buffer,
- kLoadBufferMaxSize,
- "import '%s';",
+ snprintf(load_buffer, kLoadBufferMaxSize, "import '%s';",
DartUtils::GetStringValue(library_string));
Dart_Handle script_handle = Dart_NewStringFromCString(load_buffer);
memset(load_buffer, 0, kLoadBufferMaxSize);
- snprintf(load_buffer,
- kLoadBufferMaxSize,
- "dart:_snapshot_%zu",
- lib_index);
+ snprintf(load_buffer, kLoadBufferMaxSize, "dart:_snapshot_%zu", lib_index);
Dart_Handle script_url = Dart_NewStringFromCString(load_buffer);
free(load_buffer);
- Dart_Handle loaded = Dart_LoadLibrary(script_url, Dart_Null(),
- script_handle, 0, 0);
+ Dart_Handle loaded =
+ Dart_LoadLibrary(script_url, Dart_Null(), script_handle, 0, 0);
DART_CHECK_VALID(loaded);
// Do a fresh lookup
@@ -736,9 +729,8 @@
}
DART_CHECK_VALID(library);
- Dart_Handle result = Dart_SetNativeResolver(library,
- &StubNativeLookup,
- &StubNativeSymbol);
+ Dart_Handle result =
+ Dart_SetNativeResolver(library, &StubNativeLookup, &StubNativeSymbol);
DART_CHECK_VALID(result);
}
@@ -768,7 +760,6 @@
static void SetupStubNativeResolversForPrecompilation(
const Dart_QualifiedFunctionName* entries) {
-
if (entries == NULL) {
return;
}
@@ -787,7 +778,7 @@
}
-static void CleanupEntryPointItem(const Dart_QualifiedFunctionName *entry) {
+static void CleanupEntryPointItem(const Dart_QualifiedFunctionName* entry) {
if (entry == NULL) {
return;
}
@@ -848,7 +839,9 @@
static bool ParseEntryPointsManifestSingleLine(
- const char* line, Dart_QualifiedFunctionName* entry, char** error) {
+ const char* line,
+ Dart_QualifiedFunctionName* entry,
+ char** error) {
bool success = true;
size_t offset = 0;
for (uint8_t i = 0; i < 3; i++) {
@@ -1017,20 +1010,15 @@
intptr_t isolate_size = 0;
// First create a snapshot.
- result = Dart_CreateSnapshot(&vm_isolate_buffer,
- &vm_isolate_size,
- &isolate_buffer,
- &isolate_size);
+ result = Dart_CreateSnapshot(&vm_isolate_buffer, &vm_isolate_size,
+ &isolate_buffer, &isolate_size);
CHECK_RESULT(result);
// Now write the vm isolate and isolate snapshots out to the
// specified file and exit.
- WriteSnapshotFile(vm_isolate_snapshot_filename,
- vm_isolate_buffer,
+ WriteSnapshotFile(vm_isolate_snapshot_filename, vm_isolate_buffer,
vm_isolate_size);
- WriteSnapshotFile(isolate_snapshot_filename,
- isolate_buffer,
- isolate_size);
+ WriteSnapshotFile(isolate_snapshot_filename, isolate_buffer, isolate_size);
Dart_ExitScope();
// Shutdown the isolate.
@@ -1055,9 +1043,7 @@
result = Dart_CreatePrecompiledSnapshotAssembly(&assembly_buffer,
&assembly_size);
CHECK_RESULT(result);
- WriteSnapshotFile(assembly_filename,
- assembly_buffer,
- assembly_size);
+ WriteSnapshotFile(assembly_filename, assembly_buffer, assembly_size);
} else {
uint8_t* vm_isolate_buffer = NULL;
intptr_t vm_isolate_size = 0;
@@ -1067,26 +1053,17 @@
intptr_t instructions_blob_size = 0;
uint8_t* rodata_blob_buffer = NULL;
intptr_t rodata_blob_size = 0;
- result = Dart_CreatePrecompiledSnapshotBlob(&vm_isolate_buffer,
- &vm_isolate_size,
- &isolate_buffer,
- &isolate_size,
- &instructions_blob_buffer,
- &instructions_blob_size,
- &rodata_blob_buffer,
- &rodata_blob_size);
+ result = Dart_CreatePrecompiledSnapshotBlob(
+ &vm_isolate_buffer, &vm_isolate_size, &isolate_buffer, &isolate_size,
+ &instructions_blob_buffer, &instructions_blob_size, &rodata_blob_buffer,
+ &rodata_blob_size);
CHECK_RESULT(result);
- WriteSnapshotFile(vm_isolate_snapshot_filename,
- vm_isolate_buffer,
+ WriteSnapshotFile(vm_isolate_snapshot_filename, vm_isolate_buffer,
vm_isolate_size);
- WriteSnapshotFile(isolate_snapshot_filename,
- isolate_buffer,
- isolate_size);
- WriteSnapshotFile(instructions_blob_filename,
- instructions_blob_buffer,
+ WriteSnapshotFile(isolate_snapshot_filename, isolate_buffer, isolate_size);
+ WriteSnapshotFile(instructions_blob_filename, instructions_blob_buffer,
instructions_blob_size);
- WriteSnapshotFile(rodata_blob_filename,
- rodata_blob_buffer,
+ WriteSnapshotFile(rodata_blob_filename, rodata_blob_buffer,
rodata_blob_size);
}
@@ -1136,16 +1113,11 @@
Dart_IsolateFlags* flags,
void* data,
char** error) {
- IsolateData* isolate_data = new IsolateData(script_uri,
- package_root,
- package_config);
+ IsolateData* isolate_data =
+ new IsolateData(script_uri, package_root, package_config);
Dart_Isolate isolate = NULL;
- isolate = Dart_CreateIsolate(script_uri,
- main,
- NULL,
- NULL,
- isolate_data,
- error);
+ isolate =
+ Dart_CreateIsolate(script_uri, main, NULL, NULL, isolate_data, error);
if (isolate == NULL) {
Log::PrintErr("Error: Could not create service isolate");
@@ -1168,9 +1140,7 @@
CHECK_RESULT(result);
ASSERT(Dart_IsServiceIsolate(isolate));
// Load embedder specific bits and return. Will not start http server.
- if (!VmService::Setup("127.0.0.1",
- -1,
- false /* running_precompiled */,
+ if (!VmService::Setup("127.0.0.1", -1, false /* running_precompiled */,
false /* server dev mode */)) {
*error = strdup(VmService::GetErrorMessage());
return NULL;
@@ -1194,10 +1164,7 @@
entry_points_files = &entry_points_files_array;
// Parse command line arguments.
- if (ParseArguments(argc,
- argv,
- &vm_options,
- &app_script_name) < 0) {
+ if (ParseArguments(argc, argv, &vm_options, &app_script_name) < 0) {
PrintUsage();
return 255;
}
@@ -1249,11 +1216,10 @@
return 255;
}
- IsolateData* isolate_data = new IsolateData(NULL,
- commandline_package_root,
+ IsolateData* isolate_data = new IsolateData(NULL, commandline_package_root,
commandline_packages_file);
- Dart_Isolate isolate = Dart_CreateIsolate(
- NULL, NULL, NULL, NULL, isolate_data, &error);
+ Dart_Isolate isolate =
+ Dart_CreateIsolate(NULL, NULL, NULL, NULL, isolate_data, &error);
if (isolate == NULL) {
Log::PrintErr("Error: %s", error);
free(error);
@@ -1300,8 +1266,8 @@
// Now we create an isolate into which we load all the code that needs to
// be in the snapshot.
isolate_data = new IsolateData(NULL, NULL, NULL);
- if (Dart_CreateIsolate(
- NULL, NULL, NULL, NULL, isolate_data, &error) == NULL) {
+ if (Dart_CreateIsolate(NULL, NULL, NULL, NULL, isolate_data, &error) ==
+ NULL) {
fprintf(stderr, "%s", error);
free(error);
exit(255);
diff --git a/runtime/bin/hashmap_test.cc b/runtime/bin/hashmap_test.cc
index 3a74138..47849e0 100644
--- a/runtime/bin/hashmap_test.cc
+++ b/runtime/bin/hashmap_test.cc
@@ -19,7 +19,7 @@
class IntSet {
public:
explicit IntSet(IntKeyHash hash)
- : hash_(hash), map_(HashMap::SamePointerValue, kInitialSize) {}
+ : hash_(hash), map_(HashMap::SamePointerValue, kInitialSize) {}
void Insert(int x) {
EXPECT_NE(0, x); // 0 corresponds to (void*)NULL - illegal key value
@@ -43,9 +43,7 @@
return p != NULL;
}
- void Clear() {
- map_.Clear();
- }
+ void Clear() { map_.Clear(); }
uint32_t occupancy() const {
uint32_t count = 0;
@@ -62,12 +60,24 @@
};
-static uint32_t WordHash(uint32_t key) { return dart::Utils::WordHash(key); }
-static uint32_t Hash(uint32_t key) { return 23; }
-static uint32_t CollisionHash1(uint32_t key) { return key & 0x3; }
-static uint32_t CollisionHash2(uint32_t key) { return kInitialSize - 1; }
-static uint32_t CollisionHash3(uint32_t key) { return kInitialSize - 2; }
-static uint32_t CollisionHash4(uint32_t key) { return kInitialSize - 2; }
+static uint32_t WordHash(uint32_t key) {
+ return dart::Utils::WordHash(key);
+}
+static uint32_t Hash(uint32_t key) {
+ return 23;
+}
+static uint32_t CollisionHash1(uint32_t key) {
+ return key & 0x3;
+}
+static uint32_t CollisionHash2(uint32_t key) {
+ return kInitialSize - 1;
+}
+static uint32_t CollisionHash3(uint32_t key) {
+ return kInitialSize - 2;
+}
+static uint32_t CollisionHash4(uint32_t key) {
+ return kInitialSize - 2;
+}
void TestSet(IntKeyHash hash, int size) {
diff --git a/runtime/bin/io_buffer.cc b/runtime/bin/io_buffer.cc
index 2317afa..3d671e0 100644
--- a/runtime/bin/io_buffer.cc
+++ b/runtime/bin/io_buffer.cc
@@ -7,10 +7,10 @@
namespace dart {
namespace bin {
-Dart_Handle IOBuffer::Allocate(intptr_t size, uint8_t **buffer) {
+Dart_Handle IOBuffer::Allocate(intptr_t size, uint8_t** buffer) {
uint8_t* data = Allocate(size);
- Dart_Handle result = Dart_NewExternalTypedData(
- Dart_TypedData_kUint8, data, size);
+ Dart_Handle result =
+ Dart_NewExternalTypedData(Dart_TypedData_kUint8, data, size);
Dart_NewWeakPersistentHandle(result, data, size, IOBuffer::Finalizer);
if (Dart_IsError(result)) {
diff --git a/runtime/bin/io_buffer.h b/runtime/bin/io_buffer.h
index ddd60d4..066a2b9 100644
--- a/runtime/bin/io_buffer.h
+++ b/runtime/bin/io_buffer.h
@@ -15,7 +15,7 @@
public:
// Allocate an IO buffer dart object (of type Uint8List) backed by
// an external byte array.
- static Dart_Handle Allocate(intptr_t size, uint8_t **buffer);
+ static Dart_Handle Allocate(intptr_t size, uint8_t** buffer);
// Allocate IO buffer storage.
static uint8_t* Allocate(intptr_t size);
diff --git a/runtime/bin/io_natives.cc b/runtime/bin/io_natives.cc
index 8c9c8c8..4662d82 100644
--- a/runtime/bin/io_natives.cc
+++ b/runtime/bin/io_natives.cc
@@ -157,9 +157,7 @@
const char* name_;
Dart_NativeFunction function_;
int argument_count_;
-} IOEntries[] = {
- IO_NATIVE_LIST(REGISTER_FUNCTION)
-};
+} IOEntries[] = {IO_NATIVE_LIST(REGISTER_FUNCTION)};
Dart_NativeFunction IONativeLookup(Dart_Handle name,
diff --git a/runtime/bin/io_service.cc b/runtime/bin/io_service.cc
index 491fa29..2a685f1 100644
--- a/runtime/bin/io_service.cc
+++ b/runtime/bin/io_service.cc
@@ -27,24 +27,20 @@
response = type::method##Request(data); \
break;
-void IOServiceCallback(Dart_Port dest_port_id,
- Dart_CObject* message) {
+void IOServiceCallback(Dart_Port dest_port_id, Dart_CObject* message) {
Dart_Port reply_port_id = ILLEGAL_PORT;
CObject* response = CObject::IllegalArgumentError();
CObjectArray request(message);
- if ((message->type == Dart_CObject_kArray) &&
- (request.Length() == 4) &&
- request[0]->IsInt32() &&
- request[1]->IsSendPort() &&
- request[2]->IsInt32() &&
- request[3]->IsArray()) {
+ if ((message->type == Dart_CObject_kArray) && (request.Length() == 4) &&
+ request[0]->IsInt32() && request[1]->IsSendPort() &&
+ request[2]->IsInt32() && request[3]->IsArray()) {
CObjectInt32 message_id(request[0]);
CObjectSendPort reply_port(request[1]);
CObjectInt32 request_id(request[2]);
CObjectArray data(request[3]);
reply_port_id = reply_port.Value();
switch (request_id.Value()) {
- IO_SERVICE_REQUEST_LIST(CASE_REQUEST);
+ IO_SERVICE_REQUEST_LIST(CASE_REQUEST);
default:
UNREACHABLE();
}
diff --git a/runtime/bin/io_service.h b/runtime/bin/io_service.h
index 01d6eac..7439253 100644
--- a/runtime/bin/io_service.h
+++ b/runtime/bin/io_service.h
@@ -58,14 +58,11 @@
V(Directory, Rename, 38) \
V(SSLFilter, ProcessFilter, 39)
-#define DECLARE_REQUEST(type, method, id) \
- k##type##method##Request = id,
+#define DECLARE_REQUEST(type, method, id) k##type##method##Request = id,
class IOService {
public:
- enum {
-IO_SERVICE_REQUEST_LIST(DECLARE_REQUEST)
- };
+ enum { IO_SERVICE_REQUEST_LIST(DECLARE_REQUEST) };
static Dart_Port GetServicePort();
diff --git a/runtime/bin/io_service_no_ssl.cc b/runtime/bin/io_service_no_ssl.cc
index ece9ab8..189eb03 100644
--- a/runtime/bin/io_service_no_ssl.cc
+++ b/runtime/bin/io_service_no_ssl.cc
@@ -26,24 +26,20 @@
response = type::method##Request(data); \
break;
-void IOServiceCallback(Dart_Port dest_port_id,
- Dart_CObject* message) {
+void IOServiceCallback(Dart_Port dest_port_id, Dart_CObject* message) {
Dart_Port reply_port_id = ILLEGAL_PORT;
CObject* response = CObject::IllegalArgumentError();
CObjectArray request(message);
- if ((message->type == Dart_CObject_kArray) &&
- (request.Length() == 4) &&
- request[0]->IsInt32() &&
- request[1]->IsSendPort() &&
- request[2]->IsInt32() &&
- request[3]->IsArray()) {
+ if ((message->type == Dart_CObject_kArray) && (request.Length() == 4) &&
+ request[0]->IsInt32() && request[1]->IsSendPort() &&
+ request[2]->IsInt32() && request[3]->IsArray()) {
CObjectInt32 message_id(request[0]);
CObjectSendPort reply_port(request[1]);
CObjectInt32 request_id(request[2]);
CObjectArray data(request[3]);
reply_port_id = reply_port.Value();
switch (request_id.Value()) {
- IO_SERVICE_REQUEST_LIST(CASE_REQUEST);
+ IO_SERVICE_REQUEST_LIST(CASE_REQUEST);
default:
UNREACHABLE();
}
diff --git a/runtime/bin/io_service_no_ssl.h b/runtime/bin/io_service_no_ssl.h
index ae3d0c2..125f237 100644
--- a/runtime/bin/io_service_no_ssl.h
+++ b/runtime/bin/io_service_no_ssl.h
@@ -59,14 +59,11 @@
V(Directory, ListStop, 37) \
V(Directory, Rename, 38)
-#define DECLARE_REQUEST(type, method, id) \
- k##type##method##Request = id,
+#define DECLARE_REQUEST(type, method, id) k##type##method##Request = id,
class IOService {
public:
- enum {
-IO_SERVICE_REQUEST_LIST(DECLARE_REQUEST)
- };
+ enum { IO_SERVICE_REQUEST_LIST(DECLARE_REQUEST) };
static Dart_Port GetServicePort();
diff --git a/runtime/bin/loader.cc b/runtime/bin/loader.cc
index d69def1..c94a21f 100644
--- a/runtime/bin/loader.cc
+++ b/runtime/bin/loader.cc
@@ -11,6 +11,7 @@
#include "bin/file.h"
#include "bin/lockers.h"
#include "bin/utils.h"
+#include "include/dart_tools_api.h"
namespace dart {
namespace bin {
@@ -33,9 +34,7 @@
payload_length_(0) {
monitor_ = new Monitor();
ASSERT(isolate_data_ != NULL);
- port_ = Dart_NewNativePort("Loader",
- Loader::NativeMessageHandler,
- false);
+ port_ = Dart_NewNativePort("Loader", Loader::NativeMessageHandler, false);
isolate_data_->set_loader(this);
AddLoader(port_, isolate_data_);
}
@@ -111,8 +110,7 @@
ASSERT(payload_message->value.as_typed_data.type == Dart_TypedData_kUint8);
payload_length = payload_message->value.as_typed_data.length;
payload = reinterpret_cast<uint8_t*>(malloc(payload_length));
- memmove(payload,
- payload_message->value.as_typed_data.values,
+ memmove(payload, payload_message->value.as_typed_data.values,
payload_length);
}
}
@@ -145,17 +143,16 @@
Dart_ListSetAt(request, 1, Dart_NewInteger(Dart_GetMainPortId()));
Dart_ListSetAt(request, 2, Dart_NewInteger(_Dart_kInitLoader));
Dart_ListSetAt(request, 3, Dart_NewSendPort(port_));
- Dart_ListSetAt(request, 4,
- (package_root == NULL) ? Dart_Null() :
- Dart_NewStringFromCString(package_root));
- Dart_ListSetAt(request, 5,
- (packages_file == NULL) ? Dart_Null() :
- Dart_NewStringFromCString(packages_file));
- Dart_ListSetAt(request, 6,
- Dart_NewStringFromCString(working_directory));
- Dart_ListSetAt(request, 7,
- (root_script_uri == NULL) ? Dart_Null() :
- Dart_NewStringFromCString(root_script_uri));
+ Dart_ListSetAt(request, 4, (package_root == NULL)
+ ? Dart_Null()
+ : Dart_NewStringFromCString(package_root));
+ Dart_ListSetAt(request, 5, (packages_file == NULL)
+ ? Dart_Null()
+ : Dart_NewStringFromCString(packages_file));
+ Dart_ListSetAt(request, 6, Dart_NewStringFromCString(working_directory));
+ Dart_ListSetAt(request, 7, (root_script_uri == NULL)
+ ? Dart_Null()
+ : Dart_NewStringFromCString(root_script_uri));
bool success = Dart_Post(loader_port, request);
ASSERT(success);
@@ -214,10 +211,8 @@
if (results_length_ == results_capacity_) {
// Grow to an initial capacity or double in size.
results_capacity_ = (results_capacity_ == 0) ? 4 : results_capacity_ * 2;
- results_ =
- reinterpret_cast<IOResult*>(
- realloc(results_,
- sizeof(IOResult) * results_capacity_));
+ results_ = reinterpret_cast<IOResult*>(
+ realloc(results_, sizeof(IOResult) * results_capacity_));
ASSERT(results_ != NULL);
}
ASSERT(results_ != NULL);
@@ -286,8 +281,8 @@
// isolate. The payload is a C string of the error message.
if (result->tag < 0) {
Dart_Handle library = Dart_LookupLibrary(uri);
- Dart_Handle error = Dart_NewStringFromUTF8(result->payload,
- result->payload_length);
+ Dart_Handle error =
+ Dart_NewStringFromUTF8(result->payload, result->payload_length);
// If a library with the given uri exists, give it a chance to handle
// the error. If the load requests stems from a deferred library load,
// an IO error is not fatal.
@@ -306,9 +301,9 @@
const char* lib_uri = reinterpret_cast<const char*>(result->payload);
if (strncmp(lib_uri, "http://", 7) == 0 ||
strncmp(lib_uri, "https://", 8) == 0) {
- loader->error_ =
- Dart_NewApiError("Cannot load native extensions over http: or https:");
- return false;
+ loader->error_ = Dart_NewApiError(
+ "Cannot load native extensions over http: or https:");
+ return false;
}
const char* extension_uri = reinterpret_cast<const char*>(result->uri);
const char* lib_path = NULL;
@@ -325,9 +320,8 @@
extension_path);
return false;
}
- Dart_Handle result = Extensions::LoadExtension(lib_path,
- extension_path,
- library);
+ Dart_Handle result =
+ Extensions::LoadExtension(lib_path, extension_path, library);
if (Dart_IsError(result)) {
loader->error_ = result;
return false;
@@ -342,12 +336,11 @@
DartUtils::SniffForMagicNumber(&payload, &payload_length);
Dart_Handle source = Dart_Null();
if (payload_type == DartUtils::kUnknownMagicNumber) {
- source = Dart_NewStringFromUTF8(result->payload,
- result->payload_length);
+ source = Dart_NewStringFromUTF8(result->payload, result->payload_length);
if (Dart_IsError(source)) {
- loader->error_ = DartUtils::NewError(
- "%s is not a valid UTF-8 script",
- reinterpret_cast<char*>(result->uri));
+ loader->error_ =
+ DartUtils::NewError("%s is not a valid UTF-8 script",
+ reinterpret_cast<char*>(result->uri));
return false;
}
}
@@ -361,27 +354,28 @@
loader->monitor_->Exit();
Dart_Handle dart_result = Dart_Null();
+ bool reload_extensions = false;
switch (tag) {
case Dart_kImportTag:
dart_result = Dart_LoadLibrary(uri, resolved_uri, source, 0, 0);
- break;
+ break;
case Dart_kSourceTag: {
ASSERT(library_uri != Dart_Null());
Dart_Handle library = Dart_LookupLibrary(library_uri);
ASSERT(!Dart_IsError(library));
dart_result = Dart_LoadSource(library, uri, resolved_uri, source, 0, 0);
- }
- break;
+ } break;
case Dart_kScriptTag:
if (payload_type == DartUtils::kSnapshotMagicNumber) {
dart_result = Dart_LoadScriptFromSnapshot(payload, payload_length);
+ reload_extensions = true;
} else if (payload_type == DartUtils::kKernelMagicNumber) {
dart_result = Dart_LoadKernel(payload, payload_length);
} else {
dart_result = Dart_LoadScript(uri, resolved_uri, source, 0, 0);
}
- break;
+ break;
default:
UNREACHABLE();
}
@@ -394,6 +388,15 @@
return false;
}
+ if (reload_extensions) {
+ dart_result = ReloadNativeExtensions();
+ if (Dart_IsError(dart_result)) {
+ // Remember the error if we encountered one.
+ loader->error_ = dart_result;
+ return false;
+ }
+ }
+
return true;
}
@@ -403,8 +406,8 @@
// A negative result tag indicates a loading error occurred in the service
// isolate. The payload is a C string of the error message.
if (result->tag < 0) {
- Dart_Handle error = Dart_NewStringFromUTF8(result->payload,
- result->payload_length);
+ Dart_Handle error =
+ Dart_NewStringFromUTF8(result->payload, result->payload_length);
loader->error_ = Dart_NewUnhandledExceptionError(error);
return false;
}
@@ -439,15 +442,58 @@
// Setup a loader. The constructor does a bunch of leg work.
Loader* loader = new Loader(isolate_data);
// Send the init message.
- loader->Init(isolate_data->package_root,
- isolate_data->packages_file,
- DartUtils::original_working_directory,
- snapshot_uri);
+ loader->Init(isolate_data->package_root, isolate_data->packages_file,
+ DartUtils::original_working_directory, snapshot_uri);
// Destroy the loader. The destructor does a bunch of leg work.
delete loader;
}
+#define RETURN_ERROR(result) \
+ if (Dart_IsError(result)) return result;
+
+Dart_Handle Loader::ReloadNativeExtensions() {
+ Dart_Handle scheme =
+ Dart_NewStringFromCString(DartUtils::kDartExtensionScheme);
+ Dart_Handle extension_imports = Dart_GetImportsOfScheme(scheme);
+ RETURN_ERROR(extension_imports);
+
+ intptr_t length = -1;
+ Dart_Handle result = Dart_ListLength(extension_imports, &length);
+ RETURN_ERROR(result);
+ Dart_Handle* import_handles = reinterpret_cast<Dart_Handle*>(
+ Dart_ScopeAllocate(sizeof(Dart_Handle) * length));
+ result = Dart_ListGetRange(extension_imports, 0, length, import_handles);
+ RETURN_ERROR(result);
+ for (intptr_t i = 0; i < length; i += 2) {
+ Dart_Handle importer = import_handles[i];
+ Dart_Handle importee = import_handles[i + 1];
+
+ const char* extension_uri = NULL;
+ result = Dart_StringToCString(Dart_LibraryUrl(importee), &extension_uri);
+ RETURN_ERROR(result);
+ const char* extension_path = DartUtils::RemoveScheme(extension_uri);
+
+ const char* lib_uri = NULL;
+ result = Dart_StringToCString(Dart_LibraryUrl(importer), &lib_uri);
+ RETURN_ERROR(result);
+
+ char* lib_path = NULL;
+ if (strncmp(lib_uri, "file://", 7) == 0) {
+ lib_path = DartUtils::DirName(DartUtils::RemoveScheme(lib_uri));
+ } else {
+ lib_path = strdup(lib_uri);
+ }
+
+ result = Extensions::LoadExtension(lib_path, extension_path, importer);
+ free(lib_path);
+ RETURN_ERROR(result);
+ }
+
+ return Dart_True();
+}
+
+
Dart_Handle Loader::LoadUrlContents(Dart_Handle url,
uint8_t** payload,
intptr_t* payload_length) {
@@ -459,10 +505,8 @@
// Setup the loader. The constructor does a bunch of leg work.
loader = new Loader(isolate_data);
- loader->Init(isolate_data->package_root,
- isolate_data->packages_file,
- DartUtils::original_working_directory,
- NULL);
+ loader->Init(isolate_data->package_root, isolate_data->packages_file,
+ DartUtils::original_working_directory, NULL);
ASSERT(loader != NULL);
ASSERT(isolate_data->HasLoader());
@@ -523,10 +567,7 @@
bool is_dart_library = DartUtils::IsDartSchemeURL(library_url_string);
if (is_dart_scheme_url || is_dart_library) {
- return DartColonLibraryTagHandler(tag,
- library,
- url,
- library_url_string,
+ return DartColonLibraryTagHandler(tag, library, url, library_url_string,
url_string);
}
}
@@ -563,8 +604,7 @@
// Setup the loader. The constructor does a bunch of leg work.
loader = new Loader(isolate_data);
- loader->Init(isolate_data->package_root,
- isolate_data->packages_file,
+ loader->Init(isolate_data->package_root, isolate_data->packages_file,
DartUtils::original_working_directory,
(tag == Dart_kScriptTag) ? url_string : NULL);
} else {
@@ -580,10 +620,9 @@
if (DartUtils::IsDartExtensionSchemeURL(url_string)) {
loader->SendImportExtensionRequest(url, Dart_LibraryUrl(library));
} else {
- loader->SendRequest(tag,
- url,
- (library != Dart_Null()) ?
- Dart_LibraryUrl(library) : Dart_Null());
+ loader->SendRequest(tag, url, (library != Dart_Null())
+ ? Dart_LibraryUrl(library)
+ : Dart_Null());
}
@@ -640,17 +679,21 @@
} else if (tag == Dart_kImportTag) {
Builtin::BuiltinLibraryId id = Builtin::FindId(url_string);
if (id == Builtin::kInvalidLibrary) {
- return DartUtils::NewError("The built-in library '%s' is not available"
- " on the stand-alone VM.\n", url_string);
+ return DartUtils::NewError(
+ "The built-in library '%s' is not available"
+ " on the stand-alone VM.\n",
+ url_string);
}
return Builtin::LoadLibrary(url, id);
} else {
ASSERT(tag == Dart_kSourceTag);
Builtin::BuiltinLibraryId id = Builtin::FindId(library_url_string);
if (id == Builtin::kInvalidLibrary) {
- return DartUtils::NewError("The built-in library '%s' is not available"
- " on the stand-alone VM. Trying to load"
- " '%s'.\n", library_url_string, url_string);
+ return DartUtils::NewError(
+ "The built-in library '%s' is not available"
+ " on the stand-alone VM. Trying to load"
+ " '%s'.\n",
+ library_url_string, url_string);
}
// Prepend the library URI to form a unique script URI for the part.
intptr_t len = snprintf(NULL, 0, "%s/%s", library_url_string, url_string);
@@ -658,8 +701,7 @@
snprintf(part_uri, len + 1, "%s/%s", library_url_string, url_string);
Dart_Handle part_uri_obj = DartUtils::NewString(part_uri);
free(part_uri);
- return Dart_LoadSource(library,
- part_uri_obj, Dart_Null(),
+ return Dart_LoadSource(library, part_uri_obj, Dart_Null(),
Builtin::PartSource(id, url_string), 0, 0);
}
// All cases should have been handled above.
@@ -690,10 +732,8 @@
// Grow to an initial capacity or double in size.
loader_infos_capacity_ =
(loader_infos_capacity_ == 0) ? 4 : loader_infos_capacity_ * 2;
- loader_infos_ =
- reinterpret_cast<Loader::LoaderInfo*>(
- realloc(loader_infos_,
- sizeof(Loader::LoaderInfo) * loader_infos_capacity_));
+ loader_infos_ = reinterpret_cast<Loader::LoaderInfo*>(realloc(
+ loader_infos_, sizeof(Loader::LoaderInfo) * loader_infos_capacity_));
ASSERT(loader_infos_ != NULL);
// Initialize new entries.
for (intptr_t i = loader_infos_length_; i < loader_infos_capacity_; i++) {
diff --git a/runtime/bin/loader.h b/runtime/bin/loader.h
index 6ddf49f..2076be8 100644
--- a/runtime/bin/loader.h
+++ b/runtime/bin/loader.h
@@ -22,6 +22,8 @@
static void InitForSnapshot(const char* snapshot_uri);
+ static Dart_Handle ReloadNativeExtensions();
+
// Loads contents of the specified url.
static Dart_Handle LoadUrlContents(Dart_Handle url,
uint8_t** payload,
@@ -33,9 +35,7 @@
Dart_Handle library,
Dart_Handle url);
- Dart_Handle error() const {
- return error_;
- }
+ Dart_Handle error() const { return error_; }
static void InitOnce();
@@ -86,8 +86,7 @@
const char* root_script_uri);
// Send a request for a dart-ext: import to the service isolate.
- void SendImportExtensionRequest(Dart_Handle url,
- Dart_Handle library_url);
+ void SendImportExtensionRequest(Dart_Handle url, Dart_Handle library_url);
// Send a request from the tag handler to the service isolate.
void SendRequest(Dart_LibraryTag tag,
diff --git a/runtime/bin/lockers.h b/runtime/bin/lockers.h
index 836eeda..83dd0bd 100644
--- a/runtime/bin/lockers.h
+++ b/runtime/bin/lockers.h
@@ -11,16 +11,14 @@
namespace dart {
namespace bin {
-class MutexLocker {
+class MutexLocker {
public:
explicit MutexLocker(Mutex* mutex) : mutex_(mutex) {
ASSERT(mutex != NULL);
mutex_->Lock();
}
- virtual ~MutexLocker() {
- mutex_->Unlock();
- }
+ virtual ~MutexLocker() { mutex_->Unlock(); }
private:
Mutex* const mutex_;
@@ -36,21 +34,15 @@
monitor_->Enter();
}
- virtual ~MonitorLocker() {
- monitor_->Exit();
- }
+ virtual ~MonitorLocker() { monitor_->Exit(); }
Monitor::WaitResult Wait(int64_t millis = Monitor::kNoTimeout) {
return monitor_->Wait(millis);
}
- void Notify() {
- monitor_->Notify();
- }
+ void Notify() { monitor_->Notify(); }
- void NotifyAll() {
- monitor_->NotifyAll();
- }
+ void NotifyAll() { monitor_->NotifyAll(); }
private:
Monitor* const monitor_;
diff --git a/runtime/bin/log_android.cc b/runtime/bin/log_android.cc
index 9dbbf05..7f68d68 100644
--- a/runtime/bin/log_android.cc
+++ b/runtime/bin/log_android.cc
@@ -8,7 +8,7 @@
#include "bin/log.h"
#include <android/log.h> // NOLINT
-#include <stdio.h> // NOLINT
+#include <stdio.h> // NOLINT
namespace dart {
namespace bin {
diff --git a/runtime/bin/main.cc b/runtime/bin/main.cc
index 773fdda..b481a67 100644
--- a/runtime/bin/main.cc
+++ b/runtime/bin/main.cc
@@ -223,11 +223,11 @@
}
-static bool ExtractPortAndIP(const char *option_value,
- int *out_port,
- const char **out_ip,
+static bool ExtractPortAndIP(const char* option_value,
+ int* out_port,
+ const char** out_ip,
int default_port,
- const char *default_ip) {
+ const char* default_ip) {
// [option_value] has to be one of the following formats:
// - ""
// - ":8181"
@@ -235,7 +235,7 @@
// - ":8181/192.168.0.1"
// - "=8181/192.168.0.1"
- if (*option_value== '\0') {
+ if (*option_value == '\0') {
*out_ip = default_ip;
*out_port = default_port;
return true;
@@ -246,7 +246,7 @@
}
int port = atoi(option_value + 1);
- const char *slash = strstr(option_value, "/");
+ const char* slash = strstr(option_value, "/");
if (slash == NULL) {
*out_ip = default_ip;
*out_port = port;
@@ -297,8 +297,8 @@
if (environment == NULL) {
environment = new HashMap(&HashMap::SameStringValue, 4);
}
- HashMap::Entry* entry = environment->Lookup(
- GetHashmapKeyFromString(name), HashMap::StringHash(name), true);
+ HashMap::Entry* entry = environment->Lookup(GetHashmapKeyFromString(name),
+ HashMap::StringHash(name), true);
ASSERT(entry != NULL); // Lookup adds an entry if key not found.
if (entry->value != NULL) {
free(name);
@@ -364,8 +364,10 @@
gen_snapshot_kind = kAppJIT;
return true;
}
- Log::PrintErr("Unrecognized snapshot kind: '%s'\nValid kinds are: "
- "script, app-aot, app-jit\n", kind);
+ Log::PrintErr(
+ "Unrecognized snapshot kind: '%s'\nValid kinds are: "
+ "script, app-aot, app-jit\n",
+ kind);
return false;
}
@@ -374,13 +376,12 @@
CommandLineOptions* vm_options) {
ASSERT(option_value != NULL);
- if (!ExtractPortAndIP(option_value,
- &vm_service_server_port,
- &vm_service_server_ip,
- DEFAULT_VM_SERVICE_SERVER_PORT,
+ if (!ExtractPortAndIP(option_value, &vm_service_server_port,
+ &vm_service_server_ip, DEFAULT_VM_SERVICE_SERVER_PORT,
DEFAULT_VM_SERVICE_SERVER_IP)) {
- Log::PrintErr("unrecognized --enable-vm-service option syntax. "
- "Use --enable-vm-service[=<port number>[/<IPv4 address>]]\n");
+ Log::PrintErr(
+ "unrecognized --enable-vm-service option syntax. "
+ "Use --enable-vm-service[=<port number>[/<IPv4 address>]]\n");
return false;
}
@@ -389,10 +390,12 @@
static bool ProcessDisableServiceOriginCheckOption(
- const char* option_value, CommandLineOptions* vm_options) {
+ const char* option_value,
+ CommandLineOptions* vm_options) {
ASSERT(option_value != NULL);
- Log::PrintErr("WARNING: You are running with the service protocol in an "
- "insecure mode.\n");
+ Log::PrintErr(
+ "WARNING: You are running with the service protocol in an "
+ "insecure mode.\n");
vm_service_dev_mode = true;
return true;
}
@@ -402,13 +405,12 @@
CommandLineOptions* vm_options) {
ASSERT(option_value != NULL);
- if (!ExtractPortAndIP(option_value,
- &vm_service_server_port,
- &vm_service_server_ip,
- DEFAULT_VM_SERVICE_SERVER_PORT,
+ if (!ExtractPortAndIP(option_value, &vm_service_server_port,
+ &vm_service_server_ip, DEFAULT_VM_SERVICE_SERVER_PORT,
DEFAULT_VM_SERVICE_SERVER_IP)) {
- Log::PrintErr("unrecognized --observe option syntax. "
- "Use --observe[=<port number>[/<IPv4 address>]]\n");
+ Log::PrintErr(
+ "unrecognized --observe option syntax. "
+ "Use --observe[=<port number>[/<IPv4 address>]]\n");
return false;
}
@@ -452,8 +454,8 @@
static bool ProcessHotReloadRollbackTestModeOption(
- const char* arg,
- CommandLineOptions* vm_options) {
+ const char* arg,
+ CommandLineOptions* vm_options) {
// Identity reload.
vm_options->AddArgument("--identity_reload");
// Start reloading quickly.
@@ -500,8 +502,9 @@
return false;
}
if (commandline_root_certs_cache != NULL) {
- Log::PrintErr("Only one of --root-certs-file and --root-certs-cache "
- "may be specified");
+ Log::PrintErr(
+ "Only one of --root-certs-file and --root-certs-cache "
+ "may be specified");
return false;
}
commandline_root_certs_file = arg;
@@ -510,14 +513,15 @@
static bool ProcessRootCertsCacheOption(const char* arg,
- CommandLineOptions* vm_options) {
+ CommandLineOptions* vm_options) {
ASSERT(arg != NULL);
if (*arg == '-') {
return false;
}
if (commandline_root_certs_file != NULL) {
- Log::PrintErr("Only one of --root-certs-file and --root-certs-cache "
- "may be specified");
+ Log::PrintErr(
+ "Only one of --root-certs-file and --root-certs-cache "
+ "may be specified");
return false;
}
commandline_root_certs_cache = arg;
@@ -530,36 +534,35 @@
const char* option_name;
bool (*process)(const char* option, CommandLineOptions* vm_options);
} main_options[] = {
- // Standard options shared with dart2js.
- { "-D", ProcessEnvironmentOption },
- { "-h", ProcessHelpOption },
- { "--help", ProcessHelpOption },
- { "--packages=", ProcessPackagesOption },
- { "--package-root=", ProcessPackageRootOption },
- { "-v", ProcessVerboseOption },
- { "--verbose", ProcessVerboseOption },
- { "--version", ProcessVersionOption },
+ // Standard options shared with dart2js.
+ {"-D", ProcessEnvironmentOption},
+ {"-h", ProcessHelpOption},
+ {"--help", ProcessHelpOption},
+ {"--packages=", ProcessPackagesOption},
+ {"--package-root=", ProcessPackageRootOption},
+ {"-v", ProcessVerboseOption},
+ {"--verbose", ProcessVerboseOption},
+ {"--version", ProcessVersionOption},
- // VM specific options to the standalone dart program.
- { "--compile_all", ProcessCompileAllOption },
- { "--parse_all", ProcessParseAllOption },
- { "--enable-vm-service", ProcessEnableVmServiceOption },
- { "--disable-service-origin-check", ProcessDisableServiceOriginCheckOption },
- { "--observe", ProcessObserveOption },
- { "--snapshot=", ProcessSnapshotFilenameOption },
- { "--snapshot-kind=", ProcessSnapshotKindOption },
- { "--use-blobs", ProcessUseBlobsOption },
- { "--trace-loading", ProcessTraceLoadingOption },
- { "--hot-reload-test-mode", ProcessHotReloadTestModeOption },
- { "--hot-reload-rollback-test-mode", ProcessHotReloadRollbackTestModeOption },
- { "--short_socket_read", ProcessShortSocketReadOption },
- { "--short_socket_write", ProcessShortSocketWriteOption },
+ // VM specific options to the standalone dart program.
+ {"--compile_all", ProcessCompileAllOption},
+ {"--parse_all", ProcessParseAllOption},
+ {"--enable-vm-service", ProcessEnableVmServiceOption},
+ {"--disable-service-origin-check", ProcessDisableServiceOriginCheckOption},
+ {"--observe", ProcessObserveOption},
+ {"--snapshot=", ProcessSnapshotFilenameOption},
+ {"--snapshot-kind=", ProcessSnapshotKindOption},
+ {"--use-blobs", ProcessUseBlobsOption},
+ {"--trace-loading", ProcessTraceLoadingOption},
+ {"--hot-reload-test-mode", ProcessHotReloadTestModeOption},
+ {"--hot-reload-rollback-test-mode", ProcessHotReloadRollbackTestModeOption},
+ {"--short_socket_read", ProcessShortSocketReadOption},
+ {"--short_socket_write", ProcessShortSocketWriteOption},
#if !defined(TARGET_OS_MACOS)
- { "--root-certs-file=", ProcessRootCertsFileOption },
- { "--root-certs-cache=", ProcessRootCertsCacheOption },
+ {"--root-certs-file=", ProcessRootCertsFileOption},
+ {"--root-certs-cache=", ProcessRootCertsCacheOption},
#endif // !defined(TARGET_OS_MACOS)
- { NULL, NULL }
-};
+ {NULL, NULL}};
static bool ProcessMainOptions(const char* option,
@@ -612,7 +615,7 @@
vm_options)) {
i++;
if ((argv[i] == NULL) ||
- !ProcessPackageRootOption(argv[i], vm_options)) {
+ !ProcessPackageRootOption(argv[i], vm_options)) {
Log::PrintErr("Invalid option specification : '%s'\n", argv[i - 1]);
i++;
break;
@@ -636,12 +639,10 @@
if ((strncmp(argv[i], kPrintFlags1, strlen(kPrintFlags1)) == 0) ||
(strncmp(argv[i], kPrintFlags2, strlen(kPrintFlags2)) == 0)) {
*print_flags_seen = true;
- } else if ((strncmp(argv[i],
- kVerboseDebug1,
- strlen(kVerboseDebug1)) == 0) ||
- (strncmp(argv[i],
- kVerboseDebug2,
- strlen(kVerboseDebug2)) == 0)) {
+ } else if ((strncmp(argv[i], kVerboseDebug1, strlen(kVerboseDebug1)) ==
+ 0) ||
+ (strncmp(argv[i], kVerboseDebug2, strlen(kVerboseDebug2)) ==
+ 0)) {
*verbose_debug_seen = true;
}
vm_options->AddArgument(argv[i]);
@@ -669,8 +670,9 @@
// Verify consistency of arguments.
if ((commandline_package_root != NULL) &&
(commandline_packages_file != NULL)) {
- Log::PrintErr("Specifying both a packages directory and a packages "
- "file is invalid.\n");
+ Log::PrintErr(
+ "Specifying both a packages directory and a packages "
+ "file is invalid.\n");
return -1;
}
if ((commandline_package_root != NULL) &&
@@ -692,8 +694,9 @@
return -1;
}
if ((gen_snapshot_kind != kNone) && run_app_snapshot) {
- Log::PrintErr("Specifying an option to generate a snapshot and"
- " run using a snapshot is invalid.\n");
+ Log::PrintErr(
+ "Specifying an option to generate a snapshot and"
+ " run using a snapshot is invalid.\n");
return -1;
}
@@ -708,8 +711,7 @@
return dart_arguments;
}
for (int i = 0; i < options_count; i++) {
- Dart_Handle argument_value =
- DartUtils::NewString(options->GetArgument(i));
+ Dart_Handle argument_value = DartUtils::NewString(options->GetArgument(i));
if (Dart_IsError(argument_value)) {
return argument_value;
}
@@ -736,10 +738,9 @@
name_chars[utf8_len] = '\0';
const char* value = NULL;
if (environment != NULL) {
- HashMap::Entry* entry = environment->Lookup(
- GetHashmapKeyFromString(name_chars),
- HashMap::StringHash(name_chars),
- false);
+ HashMap::Entry* entry =
+ environment->Lookup(GetHashmapKeyFromString(name_chars),
+ HashMap::StringHash(name_chars), false);
if (entry != NULL) {
value = reinterpret_cast<char*>(entry->value);
}
@@ -769,7 +770,7 @@
Dart_ExitScope(); \
Dart_ShutdownIsolate(); \
return NULL; \
- } \
+ }
static void SnapshotOnExitHook(int64_t exit_code);
@@ -798,15 +799,10 @@
return NULL;
}
- IsolateData* isolate_data = new IsolateData(script_uri,
- package_root,
- packages_config);
- Dart_Isolate isolate = Dart_CreateIsolate(script_uri,
- main,
- isolate_snapshot_buffer,
- flags,
- isolate_data,
- error);
+ IsolateData* isolate_data =
+ new IsolateData(script_uri, package_root, packages_config);
+ Dart_Isolate isolate = Dart_CreateIsolate(
+ script_uri, main, isolate_snapshot_buffer, flags, isolate_data, error);
if (isolate == NULL) {
delete isolate_data;
return NULL;
@@ -819,6 +815,10 @@
Builtin::SetNativeResolver(Builtin::kBuiltinLibrary);
Builtin::SetNativeResolver(Builtin::kIOLibrary);
}
+ if (run_app_snapshot) {
+ Dart_Handle result = Loader::ReloadNativeExtensions();
+ CHECK_RESULT(result);
+ }
// Set up the library tag handler for this isolate.
Dart_Handle result = Dart_SetLibraryTagHandler(Loader::LibraryTagHandler);
@@ -827,10 +827,8 @@
if (Dart_IsServiceIsolate(isolate)) {
// If this is the service isolate, load embedder specific bits and return.
bool skip_library_load = run_app_snapshot;
- if (!VmService::Setup(vm_service_server_ip,
- vm_service_server_port,
- skip_library_load,
- vm_service_dev_mode)) {
+ if (!VmService::Setup(vm_service_server_ip, vm_service_server_port,
+ skip_library_load, vm_service_dev_mode)) {
*error = strdup(VmService::GetErrorMessage());
return NULL;
}
@@ -838,6 +836,8 @@
result = Dart_CompileAll();
CHECK_RESULT(result);
}
+ result = Dart_SetEnvironmentCallback(EnvironmentCallback);
+ CHECK_RESULT(result);
Dart_ExitScope();
Dart_ExitIsolate();
return isolate;
@@ -872,16 +872,12 @@
Dart_Handle uri =
DartUtils::ResolveScript(Dart_NewStringFromCString(script_uri));
CHECK_RESULT(uri);
- result = Loader::LibraryTagHandler(Dart_kScriptTag,
- Dart_Null(),
- uri);
+ result = Loader::LibraryTagHandler(Dart_kScriptTag, Dart_Null(), uri);
CHECK_RESULT(result);
- Dart_TimelineEvent("LoadScript",
- Dart_TimelineGetMicros(),
- Dart_GetMainPortId(),
- Dart_Timeline_Event_Async_End,
- 0, NULL, NULL);
+ Dart_TimelineEvent("LoadScript", Dart_TimelineGetMicros(),
+ Dart_GetMainPortId(), Dart_Timeline_Event_Async_End, 0,
+ NULL, NULL);
result = DartUtils::SetupIOLibrary(script_uri);
CHECK_RESULT(result);
@@ -909,24 +905,21 @@
const char* package_root,
const char* package_config,
Dart_IsolateFlags* flags,
- void* data, char** error) {
+ void* data,
+ char** error) {
// The VM should never call the isolate helper with a NULL flags.
ASSERT(flags != NULL);
ASSERT(flags->version == DART_FLAGS_CURRENT_VERSION);
if ((package_root != NULL) && (package_config != NULL)) {
- *error = strdup("Invalid arguments - Cannot simultaneously specify "
- "package root and package map.");
+ *error = strdup(
+ "Invalid arguments - Cannot simultaneously specify "
+ "package root and package map.");
return NULL;
}
int exit_code = 0;
- return CreateIsolateAndSetupHelper(script_uri,
- main,
- package_root,
- package_config,
- flags,
- error,
- &exit_code);
+ return CreateIsolateAndSetupHelper(script_uri, main, package_root,
+ package_config, flags, error, &exit_code);
}
@@ -935,6 +928,7 @@
}
+// clang-format off
static void PrintUsage() {
Log::PrintErr(
"Usage: dart [<vm-flags>] <dart-script-file> [<dart-options>]\n"
@@ -1026,10 +1020,10 @@
Dart_SetVMFlags(1, &print_flags);
}
}
+// clang-format on
-char* BuildIsolateName(const char* script_name,
- const char* func_name) {
+char* BuildIsolateName(const char* script_name, const char* func_name) {
// Skip past any slashes in the script name.
const char* last_slash = strrchr(script_name, '/');
if (last_slash != NULL) {
@@ -1052,10 +1046,11 @@
static const char* InternalJsonRpcError(Dart_Handle error) {
TextBuffer buffer(128);
- buffer.Printf("{\"code\":-32603,"
- "\"message\":\"Internal error\","
- "\"details\": \"%s\"}",
- Dart_GetError(error));
+ buffer.Printf(
+ "{\"code\":-32603,"
+ "\"message\":\"Internal error\","
+ "\"details\": \"%s\"}",
+ Dart_GetError(error));
return buffer.Steal();
}
@@ -1067,13 +1062,12 @@
};
-static bool ServiceGetIOHandler(
- const char* method,
- const char** param_keys,
- const char** param_values,
- intptr_t num_params,
- void* user_data,
- const char** response) {
+static bool ServiceGetIOHandler(const char* method,
+ const char** param_keys,
+ const char** param_values,
+ intptr_t num_params,
+ void* user_data,
+ const char** response) {
DartScope scope;
// TODO(ajohnsen): Store the library/function in isolate data or user_data.
Dart_Handle dart_io_str = Dart_NewStringFromCString("dart:io");
@@ -1111,7 +1105,7 @@
return false;
}
- const char *json;
+ const char* json;
result = Dart_StringToCString(result, &json);
if (Dart_IsError(result)) {
*response = InternalJsonRpcError(result);
@@ -1170,8 +1164,7 @@
char* concat = NULL;
File* file = File::Open(filename, File::kWriteTruncate);
if (file == NULL) {
- ErrorExit(kErrorExitCode,
- "Unable to open file %s for writing snapshot\n",
+ ErrorExit(kErrorExitCode, "Unable to open file %s for writing snapshot\n",
filename);
}
@@ -1181,8 +1174,7 @@
}
if (!file->WriteFully(buffer, size)) {
- ErrorExit(kErrorExitCode,
- "Unable to write file %s for writing snapshot\n",
+ ErrorExit(kErrorExitCode, "Unable to write file %s for writing snapshot\n",
filename);
}
file->Release();
@@ -1231,22 +1223,22 @@
Utils::RoundUp(rodata_position + header[3], kAppSnapshotPageSize);
void* read_only_buffer =
- file->Map(File::kReadOnly, vmisolate_position,
- instructions_position - vmisolate_position);
+ file->Map(File::kReadOnly, vmisolate_position,
+ instructions_position - vmisolate_position);
if (read_only_buffer == NULL) {
Log::PrintErr("Failed to memory map snapshot\n");
Platform::Exit(kErrorExitCode);
}
- *vmisolate_buffer = reinterpret_cast<const uint8_t*>(read_only_buffer)
- + (vmisolate_position - vmisolate_position);
- *isolate_buffer = reinterpret_cast<const uint8_t*>(read_only_buffer)
- + (isolate_position - vmisolate_position);
+ *vmisolate_buffer = reinterpret_cast<const uint8_t*>(read_only_buffer) +
+ (vmisolate_position - vmisolate_position);
+ *isolate_buffer = reinterpret_cast<const uint8_t*>(read_only_buffer) +
+ (isolate_position - vmisolate_position);
if (header[3] == 0) {
*rodata_buffer = NULL;
} else {
- *rodata_buffer = reinterpret_cast<const uint8_t*>(read_only_buffer)
- + (rodata_position - vmisolate_position);
+ *rodata_buffer = reinterpret_cast<const uint8_t*>(read_only_buffer) +
+ (rodata_position - vmisolate_position);
}
if (header[4] == 0) {
@@ -1322,17 +1314,12 @@
// anyway if it was).
return false;
}
- if (ReadAppSnapshotBlobs(script_name,
- vmisolate_buffer,
- isolate_buffer,
- instructions_buffer,
- rodata_buffer)) {
+ if (ReadAppSnapshotBlobs(script_name, vmisolate_buffer, isolate_buffer,
+ instructions_buffer, rodata_buffer)) {
return true;
}
- return ReadAppSnapshotDynamicLibrary(script_name,
- vmisolate_buffer,
- isolate_buffer,
- instructions_buffer,
+ return ReadAppSnapshotDynamicLibrary(script_name, vmisolate_buffer,
+ isolate_buffer, instructions_buffer,
rodata_buffer);
}
@@ -1421,37 +1408,23 @@
Dart_Handle result;
if (use_blobs) {
result = Dart_CreatePrecompiledSnapshotBlob(
- &vm_isolate_buffer,
- &vm_isolate_size,
- &isolate_buffer,
- &isolate_size,
- &instructions_blob_buffer,
- &instructions_blob_size,
- &rodata_blob_buffer,
+ &vm_isolate_buffer, &vm_isolate_size, &isolate_buffer, &isolate_size,
+ &instructions_blob_buffer, &instructions_blob_size, &rodata_blob_buffer,
&rodata_blob_size);
} else {
- result = Dart_CreatePrecompiledSnapshotAssembly(
- &assembly_buffer,
- &assembly_size);
+ result = Dart_CreatePrecompiledSnapshotAssembly(&assembly_buffer,
+ &assembly_size);
}
if (Dart_IsError(result)) {
ErrorExit(kErrorExitCode, "%s\n", Dart_GetError(result));
}
if (use_blobs) {
- WriteAppSnapshot(snapshot_filename,
- vm_isolate_buffer,
- vm_isolate_size,
- isolate_buffer,
- isolate_size,
- instructions_blob_buffer,
- instructions_blob_size,
- rodata_blob_buffer,
+ WriteAppSnapshot(snapshot_filename, vm_isolate_buffer, vm_isolate_size,
+ isolate_buffer, isolate_size, instructions_blob_buffer,
+ instructions_blob_size, rodata_blob_buffer,
rodata_blob_size);
} else {
- WriteSnapshotFile(snapshot_filename,
- false,
- assembly_buffer,
- assembly_size);
+ WriteSnapshotFile(snapshot_filename, false, assembly_buffer, assembly_size);
}
}
@@ -1467,25 +1440,15 @@
uint8_t* rodata_blob_buffer = NULL;
intptr_t rodata_blob_size = 0;
Dart_Handle result = Dart_CreateAppJITSnapshot(
- &vm_isolate_buffer,
- &vm_isolate_size,
- &isolate_buffer,
- &isolate_size,
- &instructions_blob_buffer,
- &instructions_blob_size,
- &rodata_blob_buffer,
+ &vm_isolate_buffer, &vm_isolate_size, &isolate_buffer, &isolate_size,
+ &instructions_blob_buffer, &instructions_blob_size, &rodata_blob_buffer,
&rodata_blob_size);
if (Dart_IsError(result)) {
ErrorExit(kErrorExitCode, "%s\n", Dart_GetError(result));
}
- WriteAppSnapshot(snapshot_filename,
- vm_isolate_buffer,
- vm_isolate_size,
- isolate_buffer,
- isolate_size,
- instructions_blob_buffer,
- instructions_blob_size,
- rodata_blob_buffer,
+ WriteAppSnapshot(snapshot_filename, vm_isolate_buffer, vm_isolate_size,
+ isolate_buffer, isolate_size, instructions_blob_buffer,
+ instructions_blob_size, rodata_blob_buffer,
rodata_blob_size);
}
#endif // defined(TARGET_ARCH_X64)
@@ -1506,25 +1469,18 @@
uint8_t* isolate_buffer = NULL;
intptr_t isolate_size = 0;
- result = Dart_CreateSnapshot(&vm_isolate_buffer,
- &vm_isolate_size,
- &isolate_buffer,
- &isolate_size);
+ result = Dart_CreateSnapshot(&vm_isolate_buffer, &vm_isolate_size,
+ &isolate_buffer, &isolate_size);
if (Dart_IsError(result)) {
ErrorExit(kErrorExitCode, "%s\n", Dart_GetError(result));
}
- WriteAppSnapshot(snapshot_filename,
- vm_isolate_buffer,
- vm_isolate_size,
- isolate_buffer,
- isolate_size,
- NULL, 0, NULL, 0);
+ WriteAppSnapshot(snapshot_filename, vm_isolate_buffer, vm_isolate_size,
+ isolate_buffer, isolate_size, NULL, 0, NULL, 0);
#endif // defined(TARGET_ARCH_X64)
}
-
#define CHECK_RESULT(result) \
if (Dart_IsError(result)) { \
if (Dart_IsVMRestartRequest(result)) { \
@@ -1532,16 +1488,19 @@
Dart_ShutdownIsolate(); \
return true; \
} \
- const int exit_code = Dart_IsCompilationError(result) ? \
- kCompilationErrorExitCode : kErrorExitCode; \
+ const int exit_code = Dart_IsCompilationError(result) \
+ ? kCompilationErrorExitCode \
+ : kErrorExitCode; \
ErrorExit(exit_code, "%s\n", Dart_GetError(result)); \
}
static void SnapshotOnExitHook(int64_t exit_code) {
if (Dart_CurrentIsolate() != main_isolate) {
- Log::PrintErr("A snapshot was requested, but a secondary isolate "
- "performed a hard exit (%" Pd64 ").\n", exit_code);
+ Log::PrintErr(
+ "A snapshot was requested, but a secondary isolate "
+ "performed a hard exit (%" Pd64 ").\n",
+ exit_code);
Platform::Exit(kErrorExitCode);
}
if (exit_code == 0) {
@@ -1550,22 +1509,17 @@
}
-bool RunMainIsolate(const char* script_name,
- CommandLineOptions* dart_options) {
+bool RunMainIsolate(const char* script_name, CommandLineOptions* dart_options) {
// Call CreateIsolateAndSetup which creates an isolate and loads up
// the specified application script.
char* error = NULL;
int exit_code = 0;
char* isolate_name = BuildIsolateName(script_name, "main");
- Dart_Isolate isolate = CreateIsolateAndSetupHelper(script_name,
- "main",
- commandline_package_root,
- commandline_packages_file,
- NULL,
- &error,
- &exit_code);
+ Dart_Isolate isolate = CreateIsolateAndSetupHelper(
+ script_name, "main", commandline_package_root, commandline_packages_file,
+ NULL, &error, &exit_code);
if (isolate == NULL) {
- delete [] isolate_name;
+ delete[] isolate_name;
if (exit_code == kRestartRequestExitCode) {
free(error);
return true;
@@ -1583,7 +1537,7 @@
Platform::Exit((exit_code != 0) ? exit_code : kErrorExitCode);
}
main_isolate = isolate;
- delete [] isolate_name;
+ delete[] isolate_name;
Dart_EnterIsolate(isolate);
ASSERT(isolate == Dart_CurrentIsolate());
@@ -1601,16 +1555,14 @@
// lookup the main entry point exported from the root library.
IsolateData* isolate_data =
reinterpret_cast<IsolateData*>(Dart_IsolateData(isolate));
- result = Dart_LibraryImportLibrary(
- isolate_data->builtin_lib(), root_lib, Dart_Null());
- if (is_noopt ||
- (gen_snapshot_kind == kAppAOT) ||
+ result = Dart_LibraryImportLibrary(isolate_data->builtin_lib(), root_lib,
+ Dart_Null());
+ if (is_noopt || (gen_snapshot_kind == kAppAOT) ||
(gen_snapshot_kind == kAppJIT)) {
// Load the embedder's portion of the VM service's Dart code so it will
// be included in the app snapshot.
if (!VmService::LoadForGenPrecompiled()) {
- fprintf(stderr,
- "VM service loading failed: %s\n",
+ fprintf(stderr, "VM service loading failed: %s\n",
VmService::GetErrorMessage());
fflush(stderr);
exit(kErrorExitCode);
@@ -1633,40 +1585,40 @@
if (is_noopt || (gen_snapshot_kind == kAppAOT)) {
Dart_QualifiedFunctionName standalone_entry_points[] = {
- { "dart:_builtin", "::", "_getMainClosure" },
- { "dart:_builtin", "::", "_getPrintClosure" },
- { "dart:_builtin", "::", "_getUriBaseClosure" },
- { "dart:_builtin", "::", "_resolveInWorkingDirectory" },
- { "dart:_builtin", "::", "_setWorkingDirectory" },
- { "dart:_builtin", "::", "_setPackageRoot" },
- { "dart:_builtin", "::", "_setPackagesMap" },
- { "dart:_builtin", "::", "_libraryFilePath" },
- { "dart:io", "::", "_makeUint8ListView" },
- { "dart:io", "::", "_makeDatagram" },
- { "dart:io", "::", "_setupHooks" },
- { "dart:io", "::", "_getWatchSignalInternal" },
- { "dart:io", "CertificateException", "CertificateException." },
- { "dart:io", "Directory", "Directory." },
- { "dart:io", "File", "File." },
- { "dart:io", "FileSystemException", "FileSystemException." },
- { "dart:io", "HandshakeException", "HandshakeException." },
- { "dart:io", "Link", "Link." },
- { "dart:io", "OSError", "OSError." },
- { "dart:io", "TlsException", "TlsException." },
- { "dart:io", "X509Certificate", "X509Certificate._" },
- { "dart:io", "_ExternalBuffer", "set:data" },
- { "dart:io", "_ExternalBuffer", "get:start" },
- { "dart:io", "_ExternalBuffer", "set:start" },
- { "dart:io", "_ExternalBuffer", "get:end" },
- { "dart:io", "_ExternalBuffer", "set:end" },
- { "dart:io", "_Platform", "set:_nativeScript" },
- { "dart:io", "_ProcessStartStatus", "set:_errorCode" },
- { "dart:io", "_ProcessStartStatus", "set:_errorMessage" },
- { "dart:io", "_SecureFilterImpl", "get:buffers" },
- { "dart:io", "_SecureFilterImpl", "get:ENCRYPTED_SIZE" },
- { "dart:io", "_SecureFilterImpl", "get:SIZE" },
- { "dart:vmservice_io", "::", "main" },
- { NULL, NULL, NULL } // Must be terminated with NULL entries.
+ {"dart:_builtin", "::", "_getMainClosure"},
+ {"dart:_builtin", "::", "_getPrintClosure"},
+ {"dart:_builtin", "::", "_getUriBaseClosure"},
+ {"dart:_builtin", "::", "_resolveInWorkingDirectory"},
+ {"dart:_builtin", "::", "_setWorkingDirectory"},
+ {"dart:_builtin", "::", "_setPackageRoot"},
+ {"dart:_builtin", "::", "_setPackagesMap"},
+ {"dart:_builtin", "::", "_libraryFilePath"},
+ {"dart:io", "::", "_makeUint8ListView"},
+ {"dart:io", "::", "_makeDatagram"},
+ {"dart:io", "::", "_setupHooks"},
+ {"dart:io", "::", "_getWatchSignalInternal"},
+ {"dart:io", "CertificateException", "CertificateException."},
+ {"dart:io", "Directory", "Directory."},
+ {"dart:io", "File", "File."},
+ {"dart:io", "FileSystemException", "FileSystemException."},
+ {"dart:io", "HandshakeException", "HandshakeException."},
+ {"dart:io", "Link", "Link."},
+ {"dart:io", "OSError", "OSError."},
+ {"dart:io", "TlsException", "TlsException."},
+ {"dart:io", "X509Certificate", "X509Certificate._"},
+ {"dart:io", "_ExternalBuffer", "set:data"},
+ {"dart:io", "_ExternalBuffer", "get:start"},
+ {"dart:io", "_ExternalBuffer", "set:start"},
+ {"dart:io", "_ExternalBuffer", "get:end"},
+ {"dart:io", "_ExternalBuffer", "set:end"},
+ {"dart:io", "_Platform", "set:_nativeScript"},
+ {"dart:io", "_ProcessStartStatus", "set:_errorCode"},
+ {"dart:io", "_ProcessStartStatus", "set:_errorMessage"},
+ {"dart:io", "_SecureFilterImpl", "get:buffers"},
+ {"dart:io", "_SecureFilterImpl", "get:ENCRYPTED_SIZE"},
+ {"dart:io", "_SecureFilterImpl", "get:SIZE"},
+ {"dart:vmservice_io", "::", "main"},
+ {NULL, NULL, NULL} // Must be terminated with NULL entries.
};
const bool reset_fields = gen_snapshot_kind == kAppAOT;
@@ -1678,16 +1630,16 @@
GeneratePrecompiledSnapshot();
} else {
if (Dart_IsNull(root_lib)) {
- ErrorExit(kErrorExitCode,
- "Unable to find root library for '%s'\n",
+ ErrorExit(kErrorExitCode, "Unable to find root library for '%s'\n",
script_name);
}
// The helper function _getMainClosure creates a closure for the main
// entry point which is either explicitly or implictly exported from the
// root library.
- Dart_Handle main_closure = Dart_Invoke(isolate_data->builtin_lib(),
- Dart_NewStringFromCString("_getMainClosure"), 0, NULL);
+ Dart_Handle main_closure =
+ Dart_Invoke(isolate_data->builtin_lib(),
+ Dart_NewStringFromCString("_getMainClosure"), 0, NULL);
CHECK_RESULT(main_closure);
// Call _startIsolate in the isolate library to enable dispatching the
@@ -1737,8 +1689,10 @@
// |input| is assumed to be a gzipped stream.
// This function allocates the output buffer in the C heap and the caller
// is responsible for freeing it.
-void Decompress(const uint8_t* input, unsigned int input_len,
- uint8_t** output, unsigned int* output_length) {
+void Decompress(const uint8_t* input,
+ unsigned int input_len,
+ uint8_t** output,
+ unsigned int* output_length) {
ASSERT(input != NULL);
ASSERT(input_len > 0);
ASSERT(output != NULL);
@@ -1801,17 +1755,15 @@
Dart_Handle GetVMServiceAssetsArchiveCallback() {
uint8_t* decompressed = NULL;
unsigned int decompressed_len = 0;
- Decompress(observatory_assets_archive,
- observatory_assets_archive_len,
- &decompressed,
- &decompressed_len);
- Dart_Handle tar_file = DartUtils::MakeUint8Array(decompressed,
- decompressed_len);
+ Decompress(observatory_assets_archive, observatory_assets_archive_len,
+ &decompressed, &decompressed_len);
+ Dart_Handle tar_file =
+ DartUtils::MakeUint8Array(decompressed, decompressed_len);
// Free decompressed memory as it has been copied into a Dart array.
free(decompressed);
return tar_file;
}
-#else // !defined(DART_PRECOMPILER)
+#else // !defined(DART_PRECOMPILER)
static Dart_GetVMServiceAssetsArchive GetVMServiceAssetsArchiveCallback = NULL;
#endif // !defined(DART_PRECOMPILER)
@@ -1835,13 +1787,8 @@
bool argv_converted = ShellUtils::GetUtf8Argv(argc, argv);
// Parse command line arguments.
- if (ParseArguments(argc,
- argv,
- &vm_options,
- &script_name,
- &dart_options,
- &print_flags_seen,
- &verbose_debug_seen) < 0) {
+ if (ParseArguments(argc, argv, &vm_options, &script_name, &dart_options,
+ &print_flags_seen, &verbose_debug_seen) < 0) {
if (help_option) {
PrintUsage();
Platform::Exit(0);
@@ -1873,10 +1820,8 @@
const uint8_t* instructions_snapshot = NULL;
const uint8_t* data_snapshot = NULL;
- if (ReadAppSnapshot(script_name,
- &vm_isolate_snapshot_buffer,
- &isolate_snapshot_buffer,
- &instructions_snapshot,
+ if (ReadAppSnapshot(script_name, &vm_isolate_snapshot_buffer,
+ &isolate_snapshot_buffer, &instructions_snapshot,
&data_snapshot)) {
run_app_snapshot = true;
}
@@ -1932,8 +1877,8 @@
Platform::Exit(kErrorExitCode);
}
- Dart_RegisterIsolateServiceRequestCallback(
- "getIO", &ServiceGetIOHandler, NULL);
+ Dart_RegisterIsolateServiceRequestCallback("getIO", &ServiceGetIOHandler,
+ NULL);
Dart_SetServiceStreamCallbacks(&ServiceStreamListenCallback,
&ServiceStreamCancelCallback);
Dart_SetFileModifiedCallback(&FileModifiedCallback);
@@ -1962,8 +1907,7 @@
// Free environment if any.
if (environment != NULL) {
- for (HashMap::Entry* p = environment->Start();
- p != NULL;
+ for (HashMap::Entry* p = environment->Start(); p != NULL;
p = environment->Next(p)) {
free(p->key);
free(p->value);
diff --git a/runtime/bin/observatory_assets_empty.cc b/runtime/bin/observatory_assets_empty.cc
index 80d5fe1..e7e1738 100644
--- a/runtime/bin/observatory_assets_empty.cc
+++ b/runtime/bin/observatory_assets_empty.cc
@@ -16,7 +16,7 @@
namespace dart {
namespace bin {
-static const uint8_t observatory_assets_archive_[] = { '\0' };
+static const uint8_t observatory_assets_archive_[] = {'\0'};
unsigned int observatory_assets_archive_len = 0;
const uint8_t* observatory_assets_archive = observatory_assets_archive_;
diff --git a/runtime/bin/platform.cc b/runtime/bin/platform.cc
index 1d3814d..15bfe3d 100644
--- a/runtime/bin/platform.cc
+++ b/runtime/bin/platform.cc
@@ -94,8 +94,7 @@
intptr_t count = 0;
char** env = Platform::Environment(&count);
if (env == NULL) {
- OSError error(-1,
- "Failed to retrieve environment variables.",
+ OSError error(-1, "Failed to retrieve environment variables.",
OSError::kUnknown);
Dart_SetReturnValue(args, DartUtils::NewDartOSError(&error));
} else {
diff --git a/runtime/bin/platform.h b/runtime/bin/platform.h
index cf220e4..9dc7e7a 100644
--- a/runtime/bin/platform.h
+++ b/runtime/bin/platform.h
@@ -63,9 +63,7 @@
static void SetExecutableName(const char* executable_name) {
executable_name_ = executable_name;
}
- static const char* GetExecutableName() {
- return executable_name_;
- }
+ static const char* GetExecutableName() { return executable_name_; }
static const char* GetResolvedExecutableName() {
if (resolved_executable_name_ == NULL) {
// Try to resolve the executable path using platform specific APIs.
@@ -82,12 +80,8 @@
script_index_ = script_index;
argv_ = argv;
}
- static int GetScriptIndex() {
- return script_index_;
- }
- static char** GetArgv() {
- return argv_;
- }
+ static int GetScriptIndex() { return script_index_; }
+ static char** GetArgv() { return argv_; }
static DART_NORETURN void Exit(int exit_code);
diff --git a/runtime/bin/platform_android.cc b/runtime/bin/platform_android.cc
index 3d1a764..404f95d 100644
--- a/runtime/bin/platform_android.cc
+++ b/runtime/bin/platform_android.cc
@@ -57,7 +57,7 @@
}
-bool Platform::LocalHostname(char *buffer, intptr_t buffer_length) {
+bool Platform::LocalHostname(char* buffer, intptr_t buffer_length) {
return gethostname(buffer, buffer_length) == 0;
}
diff --git a/runtime/bin/platform_fuchsia.cc b/runtime/bin/platform_fuchsia.cc
index 3e636d1..caa5aef 100644
--- a/runtime/bin/platform_fuchsia.cc
+++ b/runtime/bin/platform_fuchsia.cc
@@ -46,7 +46,7 @@
}
-bool Platform::LocalHostname(char *buffer, intptr_t buffer_length) {
+bool Platform::LocalHostname(char* buffer, intptr_t buffer_length) {
return gethostname(buffer, buffer_length) == 0;
}
diff --git a/runtime/bin/platform_linux.cc b/runtime/bin/platform_linux.cc
index 4eb1a07..9c12c19 100644
--- a/runtime/bin/platform_linux.cc
+++ b/runtime/bin/platform_linux.cc
@@ -57,7 +57,7 @@
}
-bool Platform::LocalHostname(char *buffer, intptr_t buffer_length) {
+bool Platform::LocalHostname(char* buffer, intptr_t buffer_length) {
return gethostname(buffer, buffer_length) == 0;
}
diff --git a/runtime/bin/platform_macos.cc b/runtime/bin/platform_macos.cc
index 628056b..35e9107 100644
--- a/runtime/bin/platform_macos.cc
+++ b/runtime/bin/platform_macos.cc
@@ -9,13 +9,13 @@
#if !TARGET_OS_IOS
#include <crt_externs.h> // NOLINT
-#endif // !TARGET_OS_IOS
+#endif // !TARGET_OS_IOS
#include <mach-o/dyld.h>
-#include <signal.h> // NOLINT
-#include <string.h> // NOLINT
+#include <signal.h> // NOLINT
+#include <string.h> // NOLINT
#include <sys/sysctl.h> // NOLINT
-#include <sys/types.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <sys/types.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/fdutils.h"
#include "bin/file.h"
@@ -74,7 +74,7 @@
}
-bool Platform::LocalHostname(char *buffer, intptr_t buffer_length) {
+bool Platform::LocalHostname(char* buffer, intptr_t buffer_length) {
return gethostname(buffer, buffer_length) == 0;
}
diff --git a/runtime/bin/platform_unsupported.cc b/runtime/bin/platform_unsupported.cc
index 83893fb..64f62ef 100644
--- a/runtime/bin/platform_unsupported.cc
+++ b/runtime/bin/platform_unsupported.cc
@@ -13,55 +13,55 @@
void FUNCTION_NAME(Platform_NumberOfProcessors)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Platform is not supported on this platform"));
+ "Platform is not supported on this platform"));
}
void FUNCTION_NAME(Platform_OperatingSystem)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Platform is not supported on this platform"));
+ "Platform is not supported on this platform"));
}
void FUNCTION_NAME(Platform_PathSeparator)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Platform is not supported on this platform"));
+ "Platform is not supported on this platform"));
}
void FUNCTION_NAME(Platform_LocalHostname)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Platform is not supported on this platform"));
+ "Platform is not supported on this platform"));
}
void FUNCTION_NAME(Platform_ExecutableName)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Platform is not supported on this platform"));
+ "Platform is not supported on this platform"));
}
void FUNCTION_NAME(Platform_ResolvedExecutableName)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Platform is not supported on this platform"));
+ "Platform is not supported on this platform"));
}
void FUNCTION_NAME(Platform_ExecutableArguments)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Platform is not supported on this platform"));
+ "Platform is not supported on this platform"));
}
void FUNCTION_NAME(Platform_Environment)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Platform is not supported on this platform"));
+ "Platform is not supported on this platform"));
}
void FUNCTION_NAME(Platform_GetVersion)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewInternalError(
- "Platform is not supported on this platform"));
+ "Platform is not supported on this platform"));
}
} // namespace bin
diff --git a/runtime/bin/platform_win.cc b/runtime/bin/platform_win.cc
index c6b119d..601d4d7 100644
--- a/runtime/bin/platform_win.cc
+++ b/runtime/bin/platform_win.cc
@@ -55,7 +55,7 @@
}
-bool Platform::LocalHostname(char *buffer, intptr_t buffer_length) {
+bool Platform::LocalHostname(char* buffer, intptr_t buffer_length) {
#if defined(DART_IO_DISABLED) || defined(PLATFORM_DISABLE_SOCKET)
return false;
#else
diff --git a/runtime/bin/process.cc b/runtime/bin/process.cc
index e22e07c..9720d39 100644
--- a/runtime/bin/process.cc
+++ b/runtime/bin/process.cc
@@ -39,8 +39,8 @@
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
- result = DartUtils::SetStringField(
- status_handle, "_errorMessage", "Max argument list length exceeded");
+ result = DartUtils::SetStringField(status_handle, "_errorMessage",
+ "Max argument list length exceeded");
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
@@ -48,8 +48,8 @@
}
*length = len;
char** string_args;
- string_args = reinterpret_cast<char**>(
- Dart_ScopeAllocate(len * sizeof(*string_args)));
+ string_args =
+ reinterpret_cast<char**>(Dart_ScopeAllocate(len * sizeof(*string_args)));
for (int i = 0; i < len; i++) {
Dart_Handle arg = Dart_ListGetAt(strings, i);
if (Dart_IsError(arg)) {
@@ -60,20 +60,20 @@
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
- result = DartUtils::SetStringField(
- status_handle, "_errorMessage", error_msg);
+ result =
+ DartUtils::SetStringField(status_handle, "_errorMessage", error_msg);
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
return NULL;
}
- string_args[i] = const_cast<char *>(DartUtils::GetStringValue(arg));
+ string_args[i] = const_cast<char*>(DartUtils::GetStringValue(arg));
}
return string_args;
}
void FUNCTION_NAME(Process_Start)(Dart_NativeArguments args) {
- Dart_Handle process = Dart_GetNativeArgument(args, 0);
+ Dart_Handle process = Dart_GetNativeArgument(args, 0);
intptr_t process_stdin;
intptr_t process_stdout;
intptr_t process_stderr;
@@ -89,8 +89,8 @@
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
- result = DartUtils::SetStringField(
- status_handle, "_errorMessage", "Path must be a builtin string");
+ result = DartUtils::SetStringField(status_handle, "_errorMessage",
+ "Path must be a builtin string");
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
@@ -101,10 +101,8 @@
Dart_Handle arguments = Dart_GetNativeArgument(args, 2);
intptr_t args_length = 0;
char** string_args =
- ExtractCStringList(arguments,
- status_handle,
- "Arguments must be builtin strings",
- &args_length);
+ ExtractCStringList(arguments, status_handle,
+ "Arguments must be builtin strings", &args_length);
if (string_args == NULL) {
Dart_SetReturnValue(args, Dart_NewBoolean(false));
return;
@@ -119,9 +117,9 @@
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
- result = DartUtils::SetStringField(
- status_handle, "_errorMessage",
- "WorkingDirectory must be a builtin string");
+ result =
+ DartUtils::SetStringField(status_handle, "_errorMessage",
+ "WorkingDirectory must be a builtin string");
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
@@ -132,11 +130,9 @@
intptr_t environment_length = 0;
char** string_environment = NULL;
if (!Dart_IsNull(environment)) {
- string_environment =
- ExtractCStringList(environment,
- status_handle,
- "Environment values must be builtin strings",
- &environment_length);
+ string_environment = ExtractCStringList(
+ environment, status_handle,
+ "Environment values must be builtin strings", &environment_length);
if (string_environment == NULL) {
Dart_SetReturnValue(args, Dart_NewBoolean(false));
return;
@@ -151,19 +147,10 @@
intptr_t pid = -1;
char* os_error_message = NULL; // Scope allocated by Process::Start.
- int error_code = Process::Start(path,
- string_args,
- args_length,
- working_directory,
- string_environment,
- environment_length,
- static_cast<ProcessStartMode>(mode),
- &process_stdout,
- &process_stdin,
- &process_stderr,
- &pid,
- &exit_event,
- &os_error_message);
+ int error_code = Process::Start(
+ path, string_args, args_length, working_directory, string_environment,
+ environment_length, static_cast<ProcessStartMode>(mode), &process_stdout,
+ &process_stdin, &process_stderr, &pid, &exit_event, &os_error_message);
if (error_code == 0) {
if (mode != kDetached) {
Socket::SetSocketIdNativeField(stdin_handle, process_stdin);
@@ -175,16 +162,15 @@
}
Process::SetProcessIdNativeField(process, pid);
} else {
- result = DartUtils::SetIntegerField(
- status_handle, "_errorCode", error_code);
+ result =
+ DartUtils::SetIntegerField(status_handle, "_errorCode", error_code);
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
- result = DartUtils::SetStringField(
- status_handle,
- "_errorMessage",
- os_error_message != NULL ? os_error_message
- : "Cannot get error message");
+ result = DartUtils::SetStringField(status_handle, "_errorMessage",
+ os_error_message != NULL
+ ? os_error_message
+ : "Cannot get error message");
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
@@ -194,7 +180,7 @@
void FUNCTION_NAME(Process_Wait)(Dart_NativeArguments args) {
- Dart_Handle process = Dart_GetNativeArgument(args, 0);
+ Dart_Handle process = Dart_GetNativeArgument(args, 0);
intptr_t process_stdin =
Socket::GetSocketIdNativeField(Dart_GetNativeArgument(args, 1));
intptr_t process_stdout =
@@ -206,12 +192,8 @@
ProcessResult result;
intptr_t pid;
Process::GetProcessIdNativeField(process, &pid);
- if (Process::Wait(pid,
- process_stdin,
- process_stdout,
- process_stderr,
- exit_event,
- &result)) {
+ if (Process::Wait(pid, process_stdin, process_stdout, process_stderr,
+ exit_event, &result)) {
Dart_Handle out = result.stdout_data();
if (Dart_IsError(out)) {
Dart_PropagateError(out);
@@ -330,14 +312,13 @@
Dart_PropagateError(result);
}
intptr_t len;
- char* str = StringUtils::ConsoleStringToUtf8(
- reinterpret_cast<char*>(buffer), bytes_length, &len);
+ char* str = StringUtils::ConsoleStringToUtf8(reinterpret_cast<char*>(buffer),
+ bytes_length, &len);
if (str == NULL) {
Dart_ThrowException(
DartUtils::NewInternalError("SystemEncodingToString failed"));
}
- result =
- Dart_NewStringFromUTF8(reinterpret_cast<const uint8_t*>(str), len);
+ result = Dart_NewStringFromUTF8(reinterpret_cast<const uint8_t*>(str), len);
Dart_SetReturnValue(args, result);
}
@@ -346,8 +327,8 @@
Dart_Handle str = Dart_GetNativeArgument(args, 0);
char* utf8;
intptr_t utf8_len;
- Dart_Handle result = Dart_StringToUTF8(
- str, reinterpret_cast<uint8_t **>(&utf8), &utf8_len);
+ Dart_Handle result =
+ Dart_StringToUTF8(str, reinterpret_cast<uint8_t**>(&utf8), &utf8_len);
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
diff --git a/runtime/bin/process.h b/runtime/bin/process.h
index 4ef89290..48cf21b 100644
--- a/runtime/bin/process.h
+++ b/runtime/bin/process.h
@@ -19,12 +19,8 @@
public:
ProcessResult() : exit_code_(0) {}
- void set_stdout_data(Dart_Handle stdout_data) {
- stdout_data_ = stdout_data;
- }
- void set_stderr_data(Dart_Handle stderr_data) {
- stderr_data_ = stderr_data;
- }
+ void set_stdout_data(Dart_Handle stdout_data) { stdout_data_ = stdout_data; }
+ void set_stderr_data(Dart_Handle stderr_data) { stderr_data_ = stderr_data; }
void set_exit_code(intptr_t exit_code) { exit_code_ = exit_code; }
@@ -127,9 +123,7 @@
}
typedef void (*ExitHook)(int64_t exit_code);
- static void SetExitHook(ExitHook hook) {
- exit_hook_ = hook;
- }
+ static void SetExitHook(ExitHook hook) { exit_hook_ = hook; }
static void RunExitHook(int64_t exit_code) {
if (exit_hook_ != NULL) {
exit_hook_(exit_code);
@@ -143,8 +137,7 @@
static Dart_Handle GetProcessIdNativeField(Dart_Handle process,
intptr_t* pid);
- static Dart_Handle SetProcessIdNativeField(Dart_Handle process,
- intptr_t pid);
+ static Dart_Handle SetProcessIdNativeField(Dart_Handle process, intptr_t pid);
private:
static int global_exit_code_;
@@ -214,9 +207,7 @@
next_ = NULL;
}
- ~BufferListNode() {
- delete[] data_;
- }
+ ~BufferListNode() { delete[] data_; }
uint8_t* data_;
BufferListNode* next_;
@@ -242,8 +233,7 @@
Free();
return result;
}
- for (BufferListNode* current = head_;
- current != NULL;
+ for (BufferListNode* current = head_; current != NULL;
current = current->next_) {
intptr_t to_copy = dart::Utils::Minimum(data_size_, kBufferSize);
memmove(buffer + buffer_position, current->data_, to_copy);
diff --git a/runtime/bin/process_android.cc b/runtime/bin/process_android.cc
index 89c5bf7..b49515f 100644
--- a/runtime/bin/process_android.cc
+++ b/runtime/bin/process_android.cc
@@ -9,14 +9,14 @@
#include "bin/process.h"
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
-#include <poll.h> // NOLINT
-#include <stdio.h> // NOLINT
-#include <stdlib.h> // NOLINT
-#include <string.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <poll.h> // NOLINT
+#include <stdio.h> // NOLINT
+#include <stdlib.h> // NOLINT
+#include <string.h> // NOLINT
#include <sys/wait.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/dartutils.h"
#include "bin/fdutils.h"
@@ -27,7 +27,7 @@
#include "platform/signal_blocker.h"
#include "platform/utils.h"
-extern char **environ;
+extern char** environ;
namespace dart {
namespace bin {
@@ -42,7 +42,7 @@
// ProcessInfoList.
class ProcessInfo {
public:
- ProcessInfo(pid_t pid, intptr_t fd) : pid_(pid), fd_(fd) { }
+ ProcessInfo(pid_t pid, intptr_t fd) : pid_(pid), fd_(fd) {}
~ProcessInfo() {
int closed = TEMP_FAILURE_RETRY(close(fd_));
if (closed != 0) {
@@ -206,7 +206,7 @@
}
intptr_t exit_code_fd = ProcessInfoList::LookupProcessExitFd(pid);
if (exit_code_fd != 0) {
- int message[2] = { exit_code, negative };
+ int message[2] = {exit_code, negative};
ssize_t result =
FDUtils::WriteToBlocking(exit_code_fd, &message, sizeof(message));
// If the process has been closed, the read end of the exit
@@ -546,8 +546,8 @@
// Read exec result from child. If no data is returned the exec was
// successful and the exec call closed the pipe. Otherwise the errno
// is written to the pipe.
- bytes_read = FDUtils::ReadFromBlocking(
- exec_control_[0], &child_errno, sizeof(child_errno));
+ bytes_read = FDUtils::ReadFromBlocking(exec_control_[0], &child_errno,
+ sizeof(child_errno));
if (bytes_read == sizeof(child_errno)) {
ReadChildError();
return child_errno;
@@ -558,7 +558,7 @@
}
- int ReadDetachedExecResult(pid_t *pid) {
+ int ReadDetachedExecResult(pid_t* pid) {
int child_errno;
int bytes_read = -1;
// Read exec result from child. If only pid data is returned the exec was
@@ -621,10 +621,8 @@
max_fds = _POSIX_OPEN_MAX;
}
for (int fd = 0; fd < max_fds; fd++) {
- if ((fd != exec_control_[1]) &&
- (fd != write_out_[0]) &&
- (fd != read_in_[1]) &&
- (fd != read_err_[1])) {
+ if ((fd != exec_control_[1]) && (fd != write_out_[0]) &&
+ (fd != read_in_[1]) && (fd != read_err_[1])) {
VOID_TEMP_FAILURE_RETRY(close(fd));
}
}
@@ -674,12 +672,11 @@
const int kBufferSize = 1024;
char os_error_message[kBufferSize];
Utils::StrError(errno, os_error_message, kBufferSize);
- int bytes_written =
- FDUtils::WriteToBlocking(
- exec_control_[1], &child_errno, sizeof(child_errno));
+ int bytes_written = FDUtils::WriteToBlocking(exec_control_[1], &child_errno,
+ sizeof(child_errno));
if (bytes_written == sizeof(child_errno)) {
- FDUtils::WriteToBlocking(
- exec_control_[1], os_error_message, strlen(os_error_message) + 1);
+ FDUtils::WriteToBlocking(exec_control_[1], os_error_message,
+ strlen(os_error_message) + 1);
}
VOID_TEMP_FAILURE_RETRY(close(exec_control_[1]));
exit(1);
@@ -728,9 +725,9 @@
}
- int read_in_[2]; // Pipe for stdout to child process.
- int read_err_[2]; // Pipe for stderr to child process.
- int write_out_[2]; // Pipe for stdin to child process.
+ int read_in_[2]; // Pipe for stdout to child process.
+ int read_err_[2]; // Pipe for stderr to child process.
+ int write_out_[2]; // Pipe for stdin to child process.
int exec_control_[2]; // Pipe to get the result from exec.
char** program_arguments_;
@@ -764,24 +761,14 @@
intptr_t* id,
intptr_t* exit_event,
char** os_error_message) {
- ProcessStarter starter(path,
- arguments,
- arguments_length,
- working_directory,
- environment,
- environment_length,
- mode,
- in,
- out,
- err,
- id,
- exit_event,
- os_error_message);
+ ProcessStarter starter(path, arguments, arguments_length, working_directory,
+ environment, environment_length, mode, in, out, err,
+ id, exit_event, os_error_message);
return starter.Start();
}
-class BufferList: public BufferListBase {
+class BufferList : public BufferListBase {
public:
BufferList() {}
@@ -794,10 +781,8 @@
ASSERT(free_size_ > 0);
ASSERT(free_size_ <= kBufferSize);
intptr_t block_size = dart::Utils::Minimum(free_size_, available);
- intptr_t bytes = TEMP_FAILURE_RETRY(read(
- fd,
- reinterpret_cast<void*>(FreeSpaceAddress()),
- block_size));
+ intptr_t bytes = TEMP_FAILURE_RETRY(
+ read(fd, reinterpret_cast<void*>(FreeSpaceAddress()), block_size));
if (bytes < 0) {
return false;
}
@@ -873,8 +858,8 @@
}
} else if (fds[i].fd == exit_event) {
if (avail == 8) {
- intptr_t b = TEMP_FAILURE_RETRY(read(exit_event,
- exit_code_data.bytes, 8));
+ intptr_t b =
+ TEMP_FAILURE_RETRY(read(exit_event, exit_code_data.bytes, 8));
if (b != 8) {
return CloseProcessBuffers(fds);
}
@@ -928,13 +913,8 @@
static SignalInfo* signal_handlers = NULL;
static const int kSignalsCount = 7;
static const int kSignals[kSignalsCount] = {
- SIGHUP,
- SIGINT,
- SIGTERM,
- SIGUSR1,
- SIGUSR2,
- SIGWINCH,
- SIGQUIT // Allow VMService to listen on SIGQUIT.
+ SIGHUP, SIGINT, SIGTERM, SIGUSR1, SIGUSR2, SIGWINCH,
+ SIGQUIT // Allow VMService to listen on SIGQUIT.
};
diff --git a/runtime/bin/process_fuchsia.cc b/runtime/bin/process_fuchsia.cc
index cd2f8bf..058234f 100644
--- a/runtime/bin/process_fuchsia.cc
+++ b/runtime/bin/process_fuchsia.cc
@@ -20,8 +20,7 @@
Mutex* Process::global_exit_code_mutex_ = new Mutex();
Process::ExitHook Process::exit_hook_ = NULL;
-void Process::TerminateExitCodeHandler() {
-}
+void Process::TerminateExitCodeHandler() {}
intptr_t Process::CurrentProcessId() {
UNIMPLEMENTED();
diff --git a/runtime/bin/process_linux.cc b/runtime/bin/process_linux.cc
index fff03f9..22dc683 100644
--- a/runtime/bin/process_linux.cc
+++ b/runtime/bin/process_linux.cc
@@ -9,14 +9,14 @@
#include "bin/process.h"
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
-#include <poll.h> // NOLINT
-#include <stdio.h> // NOLINT
-#include <stdlib.h> // NOLINT
-#include <string.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <poll.h> // NOLINT
+#include <stdio.h> // NOLINT
+#include <stdlib.h> // NOLINT
+#include <string.h> // NOLINT
#include <sys/wait.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/dartutils.h"
#include "bin/fdutils.h"
@@ -27,7 +27,7 @@
#include "platform/signal_blocker.h"
#include "platform/utils.h"
-extern char **environ;
+extern char** environ;
namespace dart {
namespace bin {
@@ -42,7 +42,7 @@
// ProcessInfoList.
class ProcessInfo {
public:
- ProcessInfo(pid_t pid, intptr_t fd) : pid_(pid), fd_(fd) { }
+ ProcessInfo(pid_t pid, intptr_t fd) : pid_(pid), fd_(fd) {}
~ProcessInfo() {
int closed = TEMP_FAILURE_RETRY(close(fd_));
if (closed != 0) {
@@ -206,7 +206,7 @@
}
intptr_t exit_code_fd = ProcessInfoList::LookupProcessExitFd(pid);
if (exit_code_fd != 0) {
- int message[2] = { exit_code, negative };
+ int message[2] = {exit_code, negative};
ssize_t result =
FDUtils::WriteToBlocking(exit_code_fd, &message, sizeof(message));
// If the process has been closed, the read end of the exit
@@ -546,8 +546,8 @@
// Read exec result from child. If no data is returned the exec was
// successful and the exec call closed the pipe. Otherwise the errno
// is written to the pipe.
- bytes_read = FDUtils::ReadFromBlocking(
- exec_control_[0], &child_errno, sizeof(child_errno));
+ bytes_read = FDUtils::ReadFromBlocking(exec_control_[0], &child_errno,
+ sizeof(child_errno));
if (bytes_read == sizeof(child_errno)) {
ReadChildError();
return child_errno;
@@ -558,7 +558,7 @@
}
- int ReadDetachedExecResult(pid_t *pid) {
+ int ReadDetachedExecResult(pid_t* pid) {
int child_errno;
int bytes_read = -1;
// Read exec result from child. If only pid data is returned the exec was
@@ -621,10 +621,8 @@
max_fds = _POSIX_OPEN_MAX;
}
for (int fd = 0; fd < max_fds; fd++) {
- if ((fd != exec_control_[1]) &&
- (fd != write_out_[0]) &&
- (fd != read_in_[1]) &&
- (fd != read_err_[1])) {
+ if ((fd != exec_control_[1]) && (fd != write_out_[0]) &&
+ (fd != read_in_[1]) && (fd != read_err_[1])) {
VOID_TEMP_FAILURE_RETRY(close(fd));
}
}
@@ -674,11 +672,11 @@
const int kBufferSize = 1024;
char error_buf[kBufferSize];
char* os_error_message = Utils::StrError(errno, error_buf, kBufferSize);
- int bytes_written = FDUtils::WriteToBlocking(
- exec_control_[1], &child_errno, sizeof(child_errno));
+ int bytes_written = FDUtils::WriteToBlocking(exec_control_[1], &child_errno,
+ sizeof(child_errno));
if (bytes_written == sizeof(child_errno)) {
- FDUtils::WriteToBlocking(
- exec_control_[1], os_error_message, strlen(os_error_message) + 1);
+ FDUtils::WriteToBlocking(exec_control_[1], os_error_message,
+ strlen(os_error_message) + 1);
}
VOID_TEMP_FAILURE_RETRY(close(exec_control_[1]));
exit(1);
@@ -727,9 +725,9 @@
}
- int read_in_[2]; // Pipe for stdout to child process.
- int read_err_[2]; // Pipe for stderr to child process.
- int write_out_[2]; // Pipe for stdin to child process.
+ int read_in_[2]; // Pipe for stdout to child process.
+ int read_err_[2]; // Pipe for stderr to child process.
+ int write_out_[2]; // Pipe for stdin to child process.
int exec_control_[2]; // Pipe to get the result from exec.
char** program_arguments_;
@@ -763,24 +761,14 @@
intptr_t* id,
intptr_t* exit_event,
char** os_error_message) {
- ProcessStarter starter(path,
- arguments,
- arguments_length,
- working_directory,
- environment,
- environment_length,
- mode,
- in,
- out,
- err,
- id,
- exit_event,
- os_error_message);
+ ProcessStarter starter(path, arguments, arguments_length, working_directory,
+ environment, environment_length, mode, in, out, err,
+ id, exit_event, os_error_message);
return starter.Start();
}
-class BufferList: public BufferListBase {
+class BufferList : public BufferListBase {
public:
BufferList() {}
@@ -793,10 +781,8 @@
ASSERT(free_size_ > 0);
ASSERT(free_size_ <= kBufferSize);
intptr_t block_size = dart::Utils::Minimum(free_size_, available);
- intptr_t bytes = TEMP_FAILURE_RETRY(read(
- fd,
- reinterpret_cast<void*>(FreeSpaceAddress()),
- block_size));
+ intptr_t bytes = TEMP_FAILURE_RETRY(
+ read(fd, reinterpret_cast<void*>(FreeSpaceAddress()), block_size));
if (bytes < 0) {
return false;
}
@@ -872,8 +858,8 @@
}
} else if (fds[i].fd == exit_event) {
if (avail == 8) {
- intptr_t b = TEMP_FAILURE_RETRY(read(exit_event,
- exit_code_data.bytes, 8));
+ intptr_t b =
+ TEMP_FAILURE_RETRY(read(exit_event, exit_code_data.bytes, 8));
if (b != 8) {
return CloseProcessBuffers(fds);
}
@@ -927,13 +913,8 @@
static SignalInfo* signal_handlers = NULL;
static const int kSignalsCount = 7;
static const int kSignals[kSignalsCount] = {
- SIGHUP,
- SIGINT,
- SIGTERM,
- SIGUSR1,
- SIGUSR2,
- SIGWINCH,
- SIGQUIT // Allow VMService to listen on SIGQUIT.
+ SIGHUP, SIGINT, SIGTERM, SIGUSR1, SIGUSR2, SIGWINCH,
+ SIGQUIT // Allow VMService to listen on SIGQUIT.
};
diff --git a/runtime/bin/process_macos.cc b/runtime/bin/process_macos.cc
index 9f671a8..584968e 100644
--- a/runtime/bin/process_macos.cc
+++ b/runtime/bin/process_macos.cc
@@ -12,11 +12,11 @@
#if !TARGET_OS_IOS
#include <crt_externs.h> // NOLINT
#endif
-#include <errno.h> // NOLINT
-#include <fcntl.h> // NOLINT
-#include <poll.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <fcntl.h> // NOLINT
+#include <poll.h> // NOLINT
#include <signal.h> // NOLINT
-#include <stdio.h> // NOLINT
+#include <stdio.h> // NOLINT
#include <stdlib.h> // NOLINT
#include <string.h> // NOLINT
#include <unistd.h> // NOLINT
@@ -43,7 +43,7 @@
// ProcessInfoList.
class ProcessInfo {
public:
- ProcessInfo(pid_t pid, intptr_t fd) : pid_(pid), fd_(fd) { }
+ ProcessInfo(pid_t pid, intptr_t fd) : pid_(pid), fd_(fd) {}
~ProcessInfo() {
int closed = TEMP_FAILURE_RETRY(close(fd_));
if (closed != 0) {
@@ -207,7 +207,7 @@
}
intptr_t exit_code_fd = ProcessInfoList::LookupProcessExitFd(pid);
if (exit_code_fd != 0) {
- int message[2] = { exit_code, negative };
+ int message[2] = {exit_code, negative};
ssize_t result =
FDUtils::WriteToBlocking(exit_code_fd, &message, sizeof(message));
// If the process has been closed, the read end of the exit
@@ -562,8 +562,8 @@
// Read exec result from child. If no data is returned the exec was
// successful and the exec call closed the pipe. Otherwise the errno
// is written to the pipe.
- bytes_read = FDUtils::ReadFromBlocking(
- exec_control_[0], &child_errno, sizeof(child_errno));
+ bytes_read = FDUtils::ReadFromBlocking(exec_control_[0], &child_errno,
+ sizeof(child_errno));
if (bytes_read == sizeof(child_errno)) {
ReadChildError();
return child_errno;
@@ -574,7 +574,7 @@
}
- int ReadDetachedExecResult(pid_t *pid) {
+ int ReadDetachedExecResult(pid_t* pid) {
int child_errno;
int bytes_read = -1;
// Read exec result from child. If only pid data is returned the exec was
@@ -637,10 +637,8 @@
max_fds = _POSIX_OPEN_MAX;
}
for (int fd = 0; fd < max_fds; fd++) {
- if ((fd != exec_control_[1]) &&
- (fd != write_out_[0]) &&
- (fd != read_in_[1]) &&
- (fd != read_err_[1])) {
+ if ((fd != exec_control_[1]) && (fd != write_out_[0]) &&
+ (fd != read_in_[1]) && (fd != read_err_[1])) {
VOID_TEMP_FAILURE_RETRY(close(fd));
}
}
@@ -690,11 +688,11 @@
const int kBufferSize = 1024;
char os_error_message[kBufferSize];
Utils::StrError(errno, os_error_message, kBufferSize);
- int bytes_written = FDUtils::WriteToBlocking(
- exec_control_[1], &child_errno, sizeof(child_errno));
+ int bytes_written = FDUtils::WriteToBlocking(exec_control_[1], &child_errno,
+ sizeof(child_errno));
if (bytes_written == sizeof(child_errno)) {
- FDUtils::WriteToBlocking(
- exec_control_[1], os_error_message, strlen(os_error_message) + 1);
+ FDUtils::WriteToBlocking(exec_control_[1], os_error_message,
+ strlen(os_error_message) + 1);
}
VOID_TEMP_FAILURE_RETRY(close(exec_control_[1]));
exit(1);
@@ -743,9 +741,9 @@
}
- int read_in_[2]; // Pipe for stdout to child process.
- int read_err_[2]; // Pipe for stderr to child process.
- int write_out_[2]; // Pipe for stdin to child process.
+ int read_in_[2]; // Pipe for stdout to child process.
+ int read_err_[2]; // Pipe for stderr to child process.
+ int write_out_[2]; // Pipe for stdin to child process.
int exec_control_[2]; // Pipe to get the result from exec.
char** program_arguments_;
@@ -779,24 +777,14 @@
intptr_t* id,
intptr_t* exit_event,
char** os_error_message) {
- ProcessStarter starter(path,
- arguments,
- arguments_length,
- working_directory,
- environment,
- environment_length,
- mode,
- in,
- out,
- err,
- id,
- exit_event,
- os_error_message);
+ ProcessStarter starter(path, arguments, arguments_length, working_directory,
+ environment, environment_length, mode, in, out, err,
+ id, exit_event, os_error_message);
return starter.Start();
}
-class BufferList: public BufferListBase {
+class BufferList : public BufferListBase {
public:
BufferList() {}
@@ -809,10 +797,8 @@
ASSERT(free_size_ > 0);
ASSERT(free_size_ <= kBufferSize);
size_t block_size = dart::Utils::Minimum(free_size_, available);
- ssize_t bytes = TEMP_FAILURE_RETRY(read(
- fd,
- reinterpret_cast<void*>(FreeSpaceAddress()),
- block_size));
+ ssize_t bytes = TEMP_FAILURE_RETRY(
+ read(fd, reinterpret_cast<void*>(FreeSpaceAddress()), block_size));
if (bytes < 0) {
return false;
}
@@ -892,8 +878,8 @@
}
} else if (fds[i].fd == exit_event) {
if (avail == 8) {
- intptr_t b = TEMP_FAILURE_RETRY(read(fds[i].fd,
- exit_code_data.bytes, 8));
+ intptr_t b =
+ TEMP_FAILURE_RETRY(read(fds[i].fd, exit_code_data.bytes, 8));
if (b != 8) {
return CloseProcessBuffers(fds);
}
@@ -932,35 +918,64 @@
static int SignalMap(intptr_t id) {
switch (static_cast<ProcessSignals>(id)) {
- case kSighup: return SIGHUP;
- case kSigint: return SIGINT;
- case kSigquit: return SIGQUIT;
- case kSigill: return SIGILL;
- case kSigtrap: return SIGTRAP;
- case kSigabrt: return SIGABRT;
- case kSigbus: return SIGBUS;
- case kSigfpe: return SIGFPE;
- case kSigkill: return SIGKILL;
- case kSigusr1: return SIGUSR1;
- case kSigsegv: return SIGSEGV;
- case kSigusr2: return SIGUSR2;
- case kSigpipe: return SIGPIPE;
- case kSigalrm: return SIGALRM;
- case kSigterm: return SIGTERM;
- case kSigchld: return SIGCHLD;
- case kSigcont: return SIGCONT;
- case kSigstop: return SIGSTOP;
- case kSigtstp: return SIGTSTP;
- case kSigttin: return SIGTTIN;
- case kSigttou: return SIGTTOU;
- case kSigurg: return SIGURG;
- case kSigxcpu: return SIGXCPU;
- case kSigxfsz: return SIGXFSZ;
- case kSigvtalrm: return SIGVTALRM;
- case kSigprof: return SIGPROF;
- case kSigwinch: return SIGWINCH;
- case kSigpoll: return -1;
- case kSigsys: return SIGSYS;
+ case kSighup:
+ return SIGHUP;
+ case kSigint:
+ return SIGINT;
+ case kSigquit:
+ return SIGQUIT;
+ case kSigill:
+ return SIGILL;
+ case kSigtrap:
+ return SIGTRAP;
+ case kSigabrt:
+ return SIGABRT;
+ case kSigbus:
+ return SIGBUS;
+ case kSigfpe:
+ return SIGFPE;
+ case kSigkill:
+ return SIGKILL;
+ case kSigusr1:
+ return SIGUSR1;
+ case kSigsegv:
+ return SIGSEGV;
+ case kSigusr2:
+ return SIGUSR2;
+ case kSigpipe:
+ return SIGPIPE;
+ case kSigalrm:
+ return SIGALRM;
+ case kSigterm:
+ return SIGTERM;
+ case kSigchld:
+ return SIGCHLD;
+ case kSigcont:
+ return SIGCONT;
+ case kSigstop:
+ return SIGSTOP;
+ case kSigtstp:
+ return SIGTSTP;
+ case kSigttin:
+ return SIGTTIN;
+ case kSigttou:
+ return SIGTTOU;
+ case kSigurg:
+ return SIGURG;
+ case kSigxcpu:
+ return SIGXCPU;
+ case kSigxfsz:
+ return SIGXFSZ;
+ case kSigvtalrm:
+ return SIGVTALRM;
+ case kSigprof:
+ return SIGPROF;
+ case kSigwinch:
+ return SIGWINCH;
+ case kSigpoll:
+ return -1;
+ case kSigsys:
+ return SIGSYS;
}
return -1;
}
@@ -985,13 +1000,8 @@
static SignalInfo* signal_handlers = NULL;
static const int kSignalsCount = 7;
static const int kSignals[kSignalsCount] = {
- SIGHUP,
- SIGINT,
- SIGTERM,
- SIGUSR1,
- SIGUSR2,
- SIGWINCH,
- SIGQUIT // Allow VMService to listen on SIGQUIT.
+ SIGHUP, SIGINT, SIGTERM, SIGUSR1, SIGUSR2, SIGWINCH,
+ SIGQUIT // Allow VMService to listen on SIGQUIT.
};
@@ -1032,8 +1042,7 @@
if (NO_RETRY_EXPECTED(pipe(fds)) != 0) {
return -1;
}
- if (!FDUtils::SetCloseOnExec(fds[0]) ||
- !FDUtils::SetCloseOnExec(fds[1]) ||
+ if (!FDUtils::SetCloseOnExec(fds[0]) || !FDUtils::SetCloseOnExec(fds[1]) ||
!FDUtils::SetNonBlocking(fds[0])) {
VOID_TEMP_FAILURE_RETRY(close(fds[0]));
VOID_TEMP_FAILURE_RETRY(close(fds[1]));
diff --git a/runtime/bin/process_unsupported.cc b/runtime/bin/process_unsupported.cc
index d91b83c..c8e0bdb 100644
--- a/runtime/bin/process_unsupported.cc
+++ b/runtime/bin/process_unsupported.cc
@@ -17,79 +17,78 @@
Mutex* Process::global_exit_code_mutex_ = new Mutex();
Process::ExitHook Process::exit_hook_ = NULL;
-void Process::TerminateExitCodeHandler() {
-}
+void Process::TerminateExitCodeHandler() {}
void FUNCTION_NAME(Process_Start)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Process is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Process is not supported on this platform"));
}
void FUNCTION_NAME(Process_Wait)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Process is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Process is not supported on this platform"));
}
void FUNCTION_NAME(Process_KillPid)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Process is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Process is not supported on this platform"));
}
void FUNCTION_NAME(Process_Exit)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Process is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Process is not supported on this platform"));
}
void FUNCTION_NAME(Process_SetExitCode)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Process is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Process is not supported on this platform"));
}
void FUNCTION_NAME(Process_GetExitCode)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Process is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Process is not supported on this platform"));
}
void FUNCTION_NAME(Process_Sleep)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Process is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Process is not supported on this platform"));
}
void FUNCTION_NAME(Process_Pid)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Process is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Process is not supported on this platform"));
}
void FUNCTION_NAME(Process_SetSignalHandler)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Process is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Process is not supported on this platform"));
}
void FUNCTION_NAME(Process_ClearSignalHandler)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Process is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Process is not supported on this platform"));
}
void FUNCTION_NAME(SystemEncodingToString)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Process is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Process is not supported on this platform"));
}
void FUNCTION_NAME(StringToSystemEncoding)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewInternalError(
- "Process is not supported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewInternalError("Process is not supported on this platform"));
}
} // namespace bin
diff --git a/runtime/bin/process_win.cc b/runtime/bin/process_win.cc
index c373787..a2d93a4 100644
--- a/runtime/bin/process_win.cc
+++ b/runtime/bin/process_win.cc
@@ -45,7 +45,7 @@
: process_id_(process_id),
process_handle_(process_handle),
wait_handle_(wait_handle),
- exit_pipe_(exit_pipe) { }
+ exit_pipe_(exit_pipe) {}
~ProcessInfo() {
BOOL success = CloseHandle(process_handle_);
@@ -94,12 +94,8 @@
MutexLocker locker(mutex_);
HANDLE wait_handle = INVALID_HANDLE_VALUE;
BOOL success = RegisterWaitForSingleObject(
- &wait_handle,
- handle,
- &ExitCodeCallback,
- reinterpret_cast<void*>(pid),
- INFINITE,
- WT_EXECUTEONLYONCE);
+ &wait_handle, handle, &ExitCodeCallback, reinterpret_cast<void*>(pid),
+ INFINITE, WT_EXECUTEONLYONCE);
if (!success) {
FATAL("Failed to register exit code wait operation.");
}
@@ -177,7 +173,7 @@
exit_code = abs(exit_code);
negative = 1;
}
- int message[2] = { exit_code, negative };
+ int message[2] = {exit_code, negative};
DWORD written;
ok = WriteFile(exit_pipe, message, sizeof(message), &written, NULL);
// If the process has been closed, the read end of the exit
@@ -210,11 +206,7 @@
// Types of pipes to create.
-enum NamedPipeType {
- kInheritRead,
- kInheritWrite,
- kInheritNone
-};
+enum NamedPipeType { kInheritRead, kInheritWrite, kInheritNone };
// Create a pipe for communicating with a new process. The handles array
@@ -233,13 +225,12 @@
if (type == kInheritRead) {
handles[kWriteHandle] =
- CreateNamedPipeW(pipe_name,
- PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
+ CreateNamedPipeW(pipe_name, PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE | PIPE_WAIT,
- 1, // Number of pipes
- 1024, // Out buffer size
- 1024, // In buffer size
- 0, // Timeout in ms
+ 1, // Number of pipes
+ 1024, // Out buffer size
+ 1024, // In buffer size
+ 0, // Timeout in ms
NULL);
if (handles[kWriteHandle] == INVALID_HANDLE_VALUE) {
@@ -248,13 +239,8 @@
}
handles[kReadHandle] =
- CreateFileW(pipe_name,
- GENERIC_READ,
- 0,
- &inherit_handle,
- OPEN_EXISTING,
- FILE_READ_ATTRIBUTES | FILE_FLAG_OVERLAPPED,
- NULL);
+ CreateFileW(pipe_name, GENERIC_READ, 0, &inherit_handle, OPEN_EXISTING,
+ FILE_READ_ATTRIBUTES | FILE_FLAG_OVERLAPPED, NULL);
if (handles[kReadHandle] == INVALID_HANDLE_VALUE) {
Log::PrintErr("CreateFile failed %d\n", GetLastError());
return false;
@@ -262,13 +248,12 @@
} else {
ASSERT((type == kInheritWrite) || (type == kInheritNone));
handles[kReadHandle] =
- CreateNamedPipeW(pipe_name,
- PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,
+ CreateNamedPipeW(pipe_name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE | PIPE_WAIT,
- 1, // Number of pipes
- 1024, // Out buffer size
- 1024, // In buffer size
- 0, // Timeout in ms
+ 1, // Number of pipes
+ 1024, // Out buffer size
+ 1024, // In buffer size
+ 0, // Timeout in ms
NULL);
if (handles[kReadHandle] == INVALID_HANDLE_VALUE) {
@@ -276,14 +261,10 @@
return false;
}
- handles[kWriteHandle] =
- CreateFileW(pipe_name,
- GENERIC_WRITE,
- 0,
- (type == kInheritWrite) ? &inherit_handle : NULL,
- OPEN_EXISTING,
- FILE_WRITE_ATTRIBUTES | FILE_FLAG_OVERLAPPED,
- NULL);
+ handles[kWriteHandle] = CreateFileW(
+ pipe_name, GENERIC_WRITE, 0,
+ (type == kInheritWrite) ? &inherit_handle : NULL, OPEN_EXISTING,
+ FILE_WRITE_ATTRIBUTES | FILE_FLAG_OVERLAPPED, NULL);
if (handles[kWriteHandle] == INVALID_HANDLE_VALUE) {
Log::PrintErr("CreateFile failed %d\n", GetLastError());
return false;
@@ -332,13 +313,8 @@
inherit_handle.nLength = sizeof(SECURITY_ATTRIBUTES);
inherit_handle.bInheritHandle = TRUE;
inherit_handle.lpSecurityDescriptor = NULL;
- HANDLE nul = CreateFile(L"NUL",
- GENERIC_READ | GENERIC_WRITE,
- 0,
- &inherit_handle,
- OPEN_EXISTING,
- 0,
- NULL);
+ HANDLE nul = CreateFile(L"NUL", GENERIC_READ | GENERIC_WRITE, 0,
+ &inherit_handle, OPEN_EXISTING, 0, NULL);
if (nul == INVALID_HANDLE_VALUE) {
Log::PrintErr("CloseHandle failed %d\n", GetLastError());
}
@@ -346,15 +322,20 @@
}
-typedef BOOL (WINAPI *InitProcThreadAttrListFn)(
- LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
+typedef BOOL(WINAPI* InitProcThreadAttrListFn)(LPPROC_THREAD_ATTRIBUTE_LIST,
+ DWORD,
+ DWORD,
+ PSIZE_T);
-typedef BOOL (WINAPI *UpdateProcThreadAttrFn)(
- LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR,
- PVOID, SIZE_T, PVOID, PSIZE_T);
+typedef BOOL(WINAPI* UpdateProcThreadAttrFn)(LPPROC_THREAD_ATTRIBUTE_LIST,
+ DWORD,
+ DWORD_PTR,
+ PVOID,
+ SIZE_T,
+ PVOID,
+ PSIZE_T);
-typedef VOID (WINAPI *DeleteProcThreadAttrListFn)(
- LPPROC_THREAD_ATTRIBUTE_LIST);
+typedef VOID(WINAPI* DeleteProcThreadAttrListFn)(LPPROC_THREAD_ATTRIBUTE_LIST);
static InitProcThreadAttrListFn init_proc_thread_attr_list = NULL;
@@ -385,7 +366,7 @@
const int kMaxPipeNameSize = 80;
-template<int Count>
+template <int Count>
static int GenerateNames(wchar_t pipe_names[Count][kMaxPipeNameSize]) {
UUID uuid;
RPC_STATUS status = UuidCreateSequential(&uuid);
@@ -399,9 +380,8 @@
}
for (int i = 0; i < Count; i++) {
static const wchar_t* prefix = L"\\\\.\\Pipe\\dart";
- _snwprintf(pipe_names[i],
- kMaxPipeNameSize,
- L"%s_%s_%d", prefix, uuid_string, i + 1);
+ _snwprintf(pipe_names[i], kMaxPipeNameSize, L"%s_%s_%d", prefix,
+ uuid_string, i + 1);
}
status = RpcStringFreeW(&uuid_string);
if (status != RPC_S_OK) {
@@ -450,7 +430,7 @@
system_arguments = reinterpret_cast<wchar_t**>(
Dart_ScopeAllocate(arguments_length * sizeof(*system_arguments)));
for (int i = 0; i < arguments_length; i++) {
- system_arguments[i] = StringUtilsWin::Utf8ToWide(arguments[i]);
+ system_arguments[i] = StringUtilsWin::Utf8ToWide(arguments[i]);
}
// Compute command-line length.
@@ -462,8 +442,8 @@
command_line_length += arguments_length + 1;
// Put together command-line string.
- command_line_ = reinterpret_cast<wchar_t*>(Dart_ScopeAllocate(
- command_line_length * sizeof(*command_line_)));
+ command_line_ = reinterpret_cast<wchar_t*>(
+ Dart_ScopeAllocate(command_line_length * sizeof(*command_line_)));
int len = 0;
int remaining = command_line_length;
int written =
@@ -472,8 +452,8 @@
remaining -= written;
ASSERT(remaining >= 0);
for (int i = 0; i < arguments_length; i++) {
- written = _snwprintf(
- command_line_ + len, remaining, L" %s", system_arguments[i]);
+ written = _snwprintf(command_line_ + len, remaining, L" %s",
+ system_arguments[i]);
len += written;
remaining -= written;
ASSERT(remaining >= 0);
@@ -496,15 +476,13 @@
for (intptr_t i = 0; i < environment_length; i++) {
block_size += wcslen(system_environment[i]) + 1;
}
- environment_block_ = reinterpret_cast<wchar_t*>(Dart_ScopeAllocate(
- block_size * sizeof(*environment_block_)));
+ environment_block_ = reinterpret_cast<wchar_t*>(
+ Dart_ScopeAllocate(block_size * sizeof(*environment_block_)));
intptr_t block_index = 0;
for (intptr_t i = 0; i < environment_length; i++) {
intptr_t len = wcslen(system_environment[i]);
- intptr_t result = _snwprintf(environment_block_ + block_index,
- len,
- L"%s",
- system_environment[i]);
+ intptr_t result = _snwprintf(environment_block_ + block_index, len,
+ L"%s", system_environment[i]);
ASSERT(result == len);
block_index += len;
environment_block_[block_index++] = '\0';
@@ -565,17 +543,13 @@
return CleanupAndReturnError();
}
static const int kNumInheritedHandles = 3;
- HANDLE inherited_handles[kNumInheritedHandles] =
- { stdin_handles_[kReadHandle],
- stdout_handles_[kWriteHandle],
- stderr_handles_[kWriteHandle] };
- if (!update_proc_thread_attr(attribute_list_,
- 0,
- PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
- inherited_handles,
- kNumInheritedHandles * sizeof(HANDLE),
- NULL,
- NULL)) {
+ HANDLE inherited_handles[kNumInheritedHandles] = {
+ stdin_handles_[kReadHandle], stdout_handles_[kWriteHandle],
+ stderr_handles_[kWriteHandle]};
+ if (!update_proc_thread_attr(
+ attribute_list_, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
+ inherited_handles, kNumInheritedHandles * sizeof(HANDLE), NULL,
+ NULL)) {
return CleanupAndReturnError();
}
startup_info.lpAttributeList = attribute_list_;
@@ -590,16 +564,14 @@
if (mode_ != kNormal) {
creation_flags |= DETACHED_PROCESS;
}
- BOOL result = CreateProcessW(NULL, // ApplicationName
- command_line_,
- NULL, // ProcessAttributes
- NULL, // ThreadAttributes
- TRUE, // InheritHandles
- creation_flags,
- environment_block_,
- system_working_directory_,
- reinterpret_cast<STARTUPINFOW*>(&startup_info),
- &process_info);
+ BOOL result = CreateProcessW(
+ NULL, // ApplicationName
+ command_line_,
+ NULL, // ProcessAttributes
+ NULL, // ThreadAttributes
+ TRUE, // InheritHandles
+ creation_flags, environment_block_, system_working_directory_,
+ reinterpret_cast<STARTUPINFOW*>(&startup_info), &process_info);
if (result == 0) {
return CleanupAndReturnError();
@@ -682,8 +654,8 @@
int CleanupAndReturnError() {
int error_code = SetOsErrorMessage(os_error_message_);
- CloseProcessPipes(
- stdin_handles_, stdout_handles_, stderr_handles_, exit_handles_);
+ CloseProcessPipes(stdin_handles_, stdout_handles_, stderr_handles_,
+ exit_handles_);
return error_code;
}
@@ -727,26 +699,16 @@
intptr_t* id,
intptr_t* exit_handler,
char** os_error_message) {
- ProcessStarter starter(path,
- arguments,
- arguments_length,
- working_directory,
- environment,
- environment_length,
- mode,
- in,
- out,
- err,
- id,
- exit_handler,
- os_error_message);
+ ProcessStarter starter(path, arguments, arguments_length, working_directory,
+ environment, environment_length, mode, in, out, err,
+ id, exit_handler, os_error_message);
return starter.Start();
}
-class BufferList: public BufferListBase {
+class BufferList : public BufferListBase {
public:
- BufferList() : read_pending_(true) { }
+ BufferList() : read_pending_(true) {}
// Indicate that data has been read into the buffer provided to
// overlapped read.
@@ -771,9 +733,7 @@
read_pending_ = true;
}
- intptr_t GetDataSize() {
- return data_size_;
- }
+ intptr_t GetDataSize() { return data_size_; }
uint8_t* GetFirstDataBuffer() {
ASSERT(head_ != NULL);
@@ -782,9 +742,7 @@
return head_->data_;
}
- void FreeDataBuffer() {
- Free();
- }
+ void FreeDataBuffer() { Free(); }
private:
bool read_pending_;
@@ -803,9 +761,7 @@
ClearOverlapped();
}
- bool HasEvent(HANDLE event) {
- return (event_ == event);
- }
+ bool HasEvent(HANDLE event) { return (event_ == event); }
bool Read() {
// Get the data read as a result of a completed overlapped operation.
@@ -829,21 +785,13 @@
}
}
- Dart_Handle GetData() {
- return buffer_.GetData();
- }
+ Dart_Handle GetData() { return buffer_.GetData(); }
- intptr_t GetDataSize() {
- return buffer_.GetDataSize();
- }
+ intptr_t GetDataSize() { return buffer_.GetDataSize(); }
- uint8_t* GetFirstDataBuffer() {
- return buffer_.GetFirstDataBuffer();
- }
+ uint8_t* GetFirstDataBuffer() { return buffer_.GetFirstDataBuffer(); }
- void FreeDataBuffer() {
- return buffer_.FreeDataBuffer();
- }
+ void FreeDataBuffer() { return buffer_.FreeDataBuffer(); }
void Close() {
CloseHandle(handle_);
@@ -956,10 +904,8 @@
HANDLE wait_handle;
HANDLE exit_pipe;
// First check the process info list for the process to get a handle to it.
- bool success = ProcessInfoList::LookupProcess(id,
- &process_handle,
- &wait_handle,
- &exit_pipe);
+ bool success = ProcessInfoList::LookupProcess(id, &process_handle,
+ &wait_handle, &exit_pipe);
// For detached processes we don't have the process registered in the
// process info list. Try to look it up through the OS.
if (!success) {
@@ -1011,8 +957,10 @@
intptr_t GetWinSignal(intptr_t signal) {
switch (signal) {
- case kSighup: return CTRL_CLOSE_EVENT;
- case kSigint: return CTRL_C_EVENT;
+ case kSighup:
+ return CTRL_CLOSE_EVENT;
+ case kSigint:
+ return CTRL_C_EVENT;
default:
return -1;
}
diff --git a/runtime/bin/reference_counting.h b/runtime/bin/reference_counting.h
index 6a6a9e6..8721948 100644
--- a/runtime/bin/reference_counting.h
+++ b/runtime/bin/reference_counting.h
@@ -11,7 +11,8 @@
namespace bin {
// Forward declaration.
-template <class Target> class RefCntReleaseScope;
+template <class Target>
+class RefCntReleaseScope;
// Inherit from this class where instances of the derived class should be
// reference counted. Reference counts on instances are incremented and
@@ -32,13 +33,9 @@
template <class Derived>
class ReferenceCounted {
public:
- ReferenceCounted() :
- ref_count_(1) {
- }
+ ReferenceCounted() : ref_count_(1) {}
- ~ReferenceCounted() {
- ASSERT(ref_count_ == 0);
- }
+ ~ReferenceCounted() { ASSERT(ref_count_ == 0); }
void Retain() {
uintptr_t old = AtomicOperations::FetchAndIncrement(&ref_count_);
@@ -78,9 +75,7 @@
ASSERT(target_ != NULL);
ASSERT(target_->ref_count() > 0);
}
- ~RefCntReleaseScope() {
- target_->Release();
- }
+ ~RefCntReleaseScope() { target_->Release(); }
private:
ReferenceCounted<Target>* target_;
@@ -142,9 +137,7 @@
}
}
- Target* get() const {
- return static_cast<Target*>(target_);
- }
+ Target* get() const { return static_cast<Target*>(target_); }
private:
ReferenceCounted<Target>* target_;
diff --git a/runtime/bin/root_certificates_unsupported.cc b/runtime/bin/root_certificates_unsupported.cc
index 304a59e..1ba98c8 100644
--- a/runtime/bin/root_certificates_unsupported.cc
+++ b/runtime/bin/root_certificates_unsupported.cc
@@ -5,8 +5,7 @@
#if !defined(DART_IO_DISABLED) && !defined(DART_IO_SECURE_SOCKET_DISABLED)
#include "platform/globals.h"
-#if defined(TARGET_OS_MACOS) || \
- defined(TARGET_OS_ANDROID) || \
+#if defined(TARGET_OS_MACOS) || defined(TARGET_OS_ANDROID) || \
defined(DART_IO_ROOT_CERTS_DISABLED)
namespace dart {
diff --git a/runtime/bin/run_vm_tests.cc b/runtime/bin/run_vm_tests.cc
index 0be9565..3f621fe 100644
--- a/runtime/bin/run_vm_tests.cc
+++ b/runtime/bin/run_vm_tests.cc
@@ -55,8 +55,8 @@
if ((run_filter == kAllBenchmarks) ||
(strcmp(run_filter, this->name()) == 0)) {
this->Run();
- OS::Print("%s(%s): %" Pd64 "\n",
- this->name(), this->score_kind(), this->score());
+ OS::Print("%s(%s): %" Pd64 "\n", this->name(), this->score_kind(),
+ this->score());
run_matches++;
} else if (run_filter == kList) {
fprintf(stdout, "%s\n", this->name());
@@ -66,8 +66,9 @@
static void PrintUsage() {
- fprintf(stderr, "run_vm_tests [--list | --benchmarks | "
- "<test name> | <benchmark name>]\n");
+ fprintf(stderr,
+ "run_vm_tests [--list | --benchmarks | "
+ "<test name> | <benchmark name>]\n");
fprintf(stderr, "run_vm_tests [vm-flags ...] <test name>\n");
fprintf(stderr, "run_vm_tests [vm-flags ...] <benchmark name>\n");
}
@@ -103,19 +104,14 @@
dart_argc = argc - 2;
dart_argv = &argv[1];
}
- bool set_vm_flags_success = Flags::ProcessCommandLineFlags(dart_argc,
- dart_argv);
+ bool set_vm_flags_success =
+ Flags::ProcessCommandLineFlags(dart_argc, dart_argv);
ASSERT(set_vm_flags_success);
- const char* err_msg = Dart::InitOnce(dart::bin::vm_isolate_snapshot_buffer,
- NULL, NULL,
- NULL, NULL,
- NULL,
- dart::bin::DartUtils::OpenFile,
- dart::bin::DartUtils::ReadFile,
- dart::bin::DartUtils::WriteFile,
- dart::bin::DartUtils::CloseFile,
- NULL,
- NULL);
+ const char* err_msg = Dart::InitOnce(
+ dart::bin::vm_isolate_snapshot_buffer, NULL, NULL, NULL, NULL, NULL,
+ dart::bin::DartUtils::OpenFile, dart::bin::DartUtils::ReadFile,
+ dart::bin::DartUtils::WriteFile, dart::bin::DartUtils::CloseFile, NULL,
+ NULL);
ASSERT(err_msg == NULL);
// Apply the filter to all registered tests.
TestCaseBase::RunAll();
diff --git a/runtime/bin/run_vm_tests_fuchsia.cc b/runtime/bin/run_vm_tests_fuchsia.cc
index 3c72422..0424f8a 100644
--- a/runtime/bin/run_vm_tests_fuchsia.cc
+++ b/runtime/bin/run_vm_tests_fuchsia.cc
@@ -23,8 +23,9 @@
// tests, and then runs them.
// TODO(zra): Make this a command line argument
-const char* kRunVmTestsPath = "/boot/bin/dart_vm_tests";
+const char* kRunVmTestsPath = "/system/bin/dart_vm_tests";
+// clang-format off
// Tests that are invalid, wedge, or cause panics.
const char* kSkip[] = {
// These expect a file to exist that we aren't putting in the image.
@@ -107,7 +108,7 @@
// Needs read of RSS.
"InitialRSS",
};
-
+// clang-format on
static bool contains(const char** list, intptr_t len, const char* str) {
for (intptr_t i = 0; i < len; i++) {
@@ -120,14 +121,13 @@
static bool isSkip(const char* test) {
- return contains(
- kSkip, sizeof(kSkip) / sizeof(kSkip[0]), test);
+ return contains(kSkip, sizeof(kSkip) / sizeof(kSkip[0]), test);
}
static bool isExpectFail(const char* test) {
- return contains(
- kExpectFail, sizeof(kExpectFail) / sizeof(kExpectFail[0]), test);
+ return contains(kExpectFail, sizeof(kExpectFail) / sizeof(kExpectFail[0]),
+ test);
}
@@ -145,15 +145,18 @@
// This is mostly taken from //magenta/system/uapp/mxsh with the addtion of
// launchpad_add_pipe calls to setup pipes for stdout and stderr.
-static mx_status_t lp_setup(launchpad_t** lp_out, mx_handle_t binary_vmo,
- int argc, const char* const* argv,
- int *stdout_out, int *stderr_out) {
+static mx_status_t lp_setup(launchpad_t** lp_out,
+ mx_handle_t binary_vmo,
+ int argc,
+ const char* const* argv,
+ int* stdout_out,
+ int* stderr_out) {
if ((lp_out == NULL) || (stdout_out == NULL) || (stderr_out == NULL)) {
return ERR_INVALID_ARGS;
}
launchpad_t* lp;
mx_status_t status;
- status = launchpad_create(argv[0], &lp);
+ status = launchpad_create(0, argv[0], &lp);
RETURN_IF_ERROR(status);
status = launchpad_arguments(lp, argc, argv);
RETURN_IF_ERROR(status);
@@ -176,8 +179,10 @@
// Start the test running and return file descriptors for the stdout and stderr
// pipes.
-static mx_handle_t start_test(mx_handle_t binary_vmo, const char* test_name,
- int* stdout_out, int* stderr_out) {
+static mx_handle_t start_test(mx_handle_t binary_vmo,
+ const char* test_name,
+ int* stdout_out,
+ int* stderr_out) {
const intptr_t kArgc = 2;
const char* argv[kArgc];
@@ -187,8 +192,8 @@
launchpad_t* lp = NULL;
int stdout_pipe = -1;
int stderr_pipe = -1;
- mx_status_t status = lp_setup(
- &lp, binary_vmo, kArgc, argv, &stdout_pipe, &stderr_pipe);
+ mx_status_t status =
+ lp_setup(&lp, binary_vmo, kArgc, argv, &stdout_pipe, &stderr_pipe);
if (status != NO_ERROR) {
if (lp != NULL) {
launchpad_destroy(lp);
@@ -254,8 +259,10 @@
// Runs test 'test_name' and gives stdout and stderr for the test in
// 'test_stdout' and 'test_stderr'. Returns the exit code from the test.
-static int run_test(mx_handle_t binary_vmo, const char* test_name,
- char** test_stdout, char** test_stderr) {
+static int run_test(mx_handle_t binary_vmo,
+ const char* test_name,
+ char** test_stdout,
+ char** test_stderr) {
int stdout_pipe = -1;
int stderr_pipe = -1;
mx_handle_t p = start_test(binary_vmo, test_name, &stdout_pipe, &stderr_pipe);
@@ -264,15 +271,15 @@
drain_fd(stdout_pipe, test_stdout);
drain_fd(stderr_pipe, test_stderr);
- mx_status_t r = mx_handle_wait_one(
- p, MX_SIGNAL_SIGNALED, MX_TIME_INFINITE, NULL);
+ mx_status_t r =
+ mx_handle_wait_one(p, MX_SIGNAL_SIGNALED, MX_TIME_INFINITE, NULL);
RETURN_IF_ERROR(r);
mx_info_process_t proc_info;
mx_size_t info_size;
mx_status_t status =
- mx_object_get_info(p, MX_INFO_PROCESS, sizeof(proc_info.rec),
- &proc_info, sizeof(proc_info), &info_size);
+ mx_object_get_info(p, MX_INFO_PROCESS, sizeof(proc_info.rec), &proc_info,
+ sizeof(proc_info), &info_size);
RETURN_IF_ERROR(status);
r = mx_handle_close(p);
@@ -281,20 +288,23 @@
}
-static void handle_result(
- intptr_t result, char* test_stdout, char* test_stderr, const char* test) {
+static void handle_result(intptr_t result,
+ char* test_stdout,
+ char* test_stderr,
+ const char* test) {
if (result != 0) {
if (!isExpectFail(test) && !isBug(test)) {
- printf("**** Test %s FAILED\n\nstdout:\n%s\nstderr:\n%s\n",
- test, test_stdout, test_stderr);
+ printf("**** Test %s FAILED\n\nstdout:\n%s\nstderr:\n%s\n", test,
+ test_stdout, test_stderr);
} else {
printf("Test %s FAILED and is expected to fail\n", test);
}
} else {
if (isExpectFail(test)) {
- printf("**** Test %s is expected to fail, but PASSED\n\n"
- "stdout:\n%s\nstderr:\n%s\n",
- test, test_stdout, test_stderr);
+ printf(
+ "**** Test %s is expected to fail, but PASSED\n\n"
+ "stdout:\n%s\nstderr:\n%s\n",
+ test, test_stdout, test_stderr);
} else if (isBug(test)) {
printf("**** Test %s is marked as a bug, but PASSED\n", test);
} else {
diff --git a/runtime/bin/secure_socket.h b/runtime/bin/secure_socket.h
index e01df41..1af6197 100644
--- a/runtime/bin/secure_socket.h
+++ b/runtime/bin/secure_socket.h
@@ -10,8 +10,7 @@
#endif
#include "platform/globals.h"
-#if defined(TARGET_OS_ANDROID) || \
- defined(TARGET_OS_LINUX) || \
+#if defined(TARGET_OS_ANDROID) || defined(TARGET_OS_LINUX) || \
defined(TARGET_OS_WINDOWS)
#include "bin/secure_socket_boringssl.h"
#elif defined(TARGET_OS_MACOS)
diff --git a/runtime/bin/secure_socket_boringssl.cc b/runtime/bin/secure_socket_boringssl.cc
index 83f96d2..68d68ee 100644
--- a/runtime/bin/secure_socket_boringssl.cc
+++ b/runtime/bin/secure_socket_boringssl.cc
@@ -5,8 +5,7 @@
#if !defined(DART_IO_DISABLED) && !defined(DART_IO_SECURE_SOCKET_DISABLED)
#include "platform/globals.h"
-#if defined(TARGET_OS_ANDROID) || \
- defined(TARGET_OS_LINUX) || \
+#if defined(TARGET_OS_ANDROID) || defined(TARGET_OS_LINUX) || \
defined(TARGET_OS_WINDOWS)
#include "bin/secure_socket.h"
@@ -117,18 +116,16 @@
SSLFilter* filter;
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
ASSERT(Dart_IsInstance(dart_this));
- ThrowIfError(Dart_GetNativeInstanceField(
- dart_this,
- kSSLFilterNativeFieldIndex,
- reinterpret_cast<intptr_t*>(&filter)));
+ ThrowIfError(
+ Dart_GetNativeInstanceField(dart_this, kSSLFilterNativeFieldIndex,
+ reinterpret_cast<intptr_t*>(&filter)));
return filter;
}
-static void DeleteFilter(
- void* isolate_data,
- Dart_WeakPersistentHandle handle,
- void* context_pointer) {
+static void DeleteFilter(void* isolate_data,
+ Dart_WeakPersistentHandle handle,
+ void* context_pointer) {
SSLFilter* filter = reinterpret_cast<SSLFilter*>(context_pointer);
filter->Release();
}
@@ -139,15 +136,12 @@
Dart_Handle dart_this = Dart_GetNativeArgument(args, 0);
RETURN_IF_ERROR(dart_this);
ASSERT(Dart_IsInstance(dart_this));
- Dart_Handle err = Dart_SetNativeInstanceField(
- dart_this,
- kSSLFilterNativeFieldIndex,
- reinterpret_cast<intptr_t>(filter));
+ Dart_Handle err =
+ Dart_SetNativeInstanceField(dart_this, kSSLFilterNativeFieldIndex,
+ reinterpret_cast<intptr_t>(filter));
RETURN_IF_ERROR(err);
- Dart_NewWeakPersistentHandle(dart_this,
- reinterpret_cast<void*>(filter),
- sizeof(*filter),
- DeleteFilter);
+ Dart_NewWeakPersistentHandle(dart_this, reinterpret_cast<void*>(filter),
+ sizeof(*filter), DeleteFilter);
return Dart_Null();
}
@@ -156,18 +150,16 @@
SSLContext* context;
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
ASSERT(Dart_IsInstance(dart_this));
- ThrowIfError(Dart_GetNativeInstanceField(
- dart_this,
- kSecurityContextNativeFieldIndex,
- reinterpret_cast<intptr_t*>(&context)));
+ ThrowIfError(
+ Dart_GetNativeInstanceField(dart_this, kSecurityContextNativeFieldIndex,
+ reinterpret_cast<intptr_t*>(&context)));
return context;
}
-static void DeleteSecurityContext(
- void* isolate_data,
- Dart_WeakPersistentHandle handle,
- void* context_pointer) {
+static void DeleteSecurityContext(void* isolate_data,
+ Dart_WeakPersistentHandle handle,
+ void* context_pointer) {
SSLContext* context = static_cast<SSLContext*>(context_pointer);
delete context;
}
@@ -179,14 +171,11 @@
Dart_Handle dart_this = Dart_GetNativeArgument(args, 0);
RETURN_IF_ERROR(dart_this);
ASSERT(Dart_IsInstance(dart_this));
- Dart_Handle err = Dart_SetNativeInstanceField(
- dart_this,
- kSecurityContextNativeFieldIndex,
- reinterpret_cast<intptr_t>(context));
+ Dart_Handle err =
+ Dart_SetNativeInstanceField(dart_this, kSecurityContextNativeFieldIndex,
+ reinterpret_cast<intptr_t>(context));
RETURN_IF_ERROR(err);
- Dart_NewWeakPersistentHandle(dart_this,
- context,
- approximate_size_of_context,
+ Dart_NewWeakPersistentHandle(dart_this, context, approximate_size_of_context,
DeleteSecurityContext);
return Dart_Null();
}
@@ -196,10 +185,9 @@
X509* certificate;
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
ASSERT(Dart_IsInstance(dart_this));
- ThrowIfError(Dart_GetNativeInstanceField(
- dart_this,
- kX509NativeFieldIndex,
- reinterpret_cast<intptr_t*>(&certificate)));
+ ThrowIfError(
+ Dart_GetNativeInstanceField(dart_this, kX509NativeFieldIndex,
+ reinterpret_cast<intptr_t*>(&certificate)));
return certificate;
}
@@ -237,8 +225,7 @@
DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 4));
bool require_client_certificate =
DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 5));
- Dart_Handle protocols_handle =
- ThrowIfError(Dart_GetNativeArgument(args, 6));
+ Dart_Handle protocols_handle = ThrowIfError(Dart_GetNativeArgument(args, 6));
const char* host_name = NULL;
// TODO(whesse): Is truncating a Dart string containing \0 what we want?
@@ -247,8 +234,7 @@
SSLContext* context = NULL;
if (!Dart_IsNull(context_object)) {
ThrowIfError(Dart_GetNativeInstanceField(
- context_object,
- kSecurityContextNativeFieldIndex,
+ context_object, kSecurityContextNativeFieldIndex,
reinterpret_cast<intptr_t*>(&context)));
}
@@ -256,12 +242,9 @@
// It will have the correct length encoding of the protocols array.
ASSERT(!Dart_IsNull(protocols_handle));
- GetFilter(args)->Connect(host_name,
- context->context(),
- is_server,
+ GetFilter(args)->Connect(host_name, context->context(), is_server,
request_client_certificate,
- require_client_certificate,
- protocols_handle);
+ require_client_certificate, protocols_handle);
}
@@ -295,8 +278,7 @@
DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 2));
bool require_client_certificate =
DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 3));
- GetFilter(args)->Renegotiate(use_session_cache,
- request_client_certificate,
+ GetFilter(args)->Renegotiate(use_session_cache, request_client_certificate,
require_client_certificate);
}
@@ -315,8 +297,7 @@
void FUNCTION_NAME(SecureSocket_RegisterBadCertificateCallback)(
Dart_NativeArguments args) {
- Dart_Handle callback =
- ThrowIfError(Dart_GetNativeArgument(args, 1));
+ Dart_Handle callback = ThrowIfError(Dart_GetNativeArgument(args, 1));
if (!Dart_IsClosure(callback) && !Dart_IsNull(callback)) {
Dart_ThrowException(DartUtils::NewDartArgumentError(
"Illegal argument to RegisterBadCertificateCallback"));
@@ -325,8 +306,7 @@
}
-void FUNCTION_NAME(SecureSocket_PeerCertificate)
- (Dart_NativeArguments args) {
+void FUNCTION_NAME(SecureSocket_PeerCertificate)(Dart_NativeArguments args) {
Dart_Handle cert = ThrowIfError(GetFilter(args)->PeerCertificate());
Dart_SetReturnValue(args, cert);
}
@@ -342,10 +322,9 @@
}
-static void ReleaseCertificate(
- void* isolate_data,
- Dart_WeakPersistentHandle handle,
- void* context_pointer) {
+static void ReleaseCertificate(void* isolate_data,
+ Dart_WeakPersistentHandle handle,
+ void* context_pointer) {
X509* cert = reinterpret_cast<X509*>(context_pointer);
X509_free(cert);
}
@@ -365,7 +344,7 @@
X509_free(certificate);
return x509_type;
}
- Dart_Handle arguments[] = { NULL };
+ Dart_Handle arguments[] = {NULL};
Dart_Handle result =
Dart_New(x509_type, DartUtils::NewString("_"), 0, arguments);
if (Dart_IsError(result)) {
@@ -374,15 +353,12 @@
}
ASSERT(Dart_IsInstance(result));
Dart_Handle status = Dart_SetNativeInstanceField(
- result,
- kX509NativeFieldIndex,
- reinterpret_cast<intptr_t>(certificate));
+ result, kX509NativeFieldIndex, reinterpret_cast<intptr_t>(certificate));
if (Dart_IsError(status)) {
X509_free(certificate);
return status;
}
- Dart_NewWeakPersistentHandle(result,
- reinterpret_cast<void*>(certificate),
+ Dart_NewWeakPersistentHandle(result, reinterpret_cast<void*>(certificate),
approximate_size_of_certificate,
ReleaseCertificate);
return result;
@@ -399,8 +375,8 @@
}
X509* certificate = X509_STORE_CTX_get_current_cert(store_ctx);
int ssl_index = SSL_get_ex_data_X509_STORE_CTX_idx();
- SSL* ssl = static_cast<SSL*>(
- X509_STORE_CTX_get_ex_data(store_ctx, ssl_index));
+ SSL* ssl =
+ static_cast<SSL*>(X509_STORE_CTX_get_ex_data(store_ctx, ssl_index));
SSLFilter* filter = static_cast<SSLFilter*>(
SSL_get_ex_data(ssl, SSLFilter::filter_ssl_index));
Dart_Handle callback = filter->bad_certificate_callback();
@@ -484,8 +460,8 @@
public:
explicit ScopedMemBIO(Dart_Handle object) {
if (!Dart_IsTypedData(object) && !Dart_IsList(object)) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Argument is not a List<int>"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Argument is not a List<int>"));
}
uint8_t* bytes = NULL;
@@ -495,10 +471,7 @@
is_typed_data = true;
Dart_TypedData_Type typ;
ThrowIfError(Dart_TypedDataAcquireData(
- object,
- &typ,
- reinterpret_cast<void**>(&bytes),
- &bytes_len));
+ object, &typ, reinterpret_cast<void**>(&bytes), &bytes_len));
} else {
ASSERT(Dart_IsList(object));
ThrowIfError(Dart_ListLength(object, &bytes_len));
@@ -541,7 +514,7 @@
DISALLOW_COPY_AND_ASSIGN(ScopedMemBIO);
};
-template<typename T, void (*free_func)(T*)>
+template <typename T, void (*free_func)(T*)>
class ScopedSSLType {
public:
explicit ScopedSSLType(T* obj) : obj_(obj) {}
@@ -568,7 +541,7 @@
DISALLOW_COPY_AND_ASSIGN(ScopedSSLType);
};
-template<typename T, typename E, void (*func)(E*)>
+template <typename T, typename E, void (*func)(E*)>
class ScopedSSLStackType {
public:
explicit ScopedSSLStackType(T* obj) : obj_(obj) {}
@@ -576,7 +549,7 @@
~ScopedSSLStackType() {
if (obj_ != NULL) {
sk_pop_free(reinterpret_cast<_STACK*>(obj_),
- reinterpret_cast<void (*)(void *)>(func));
+ reinterpret_cast<void (*)(void*)>(func));
}
}
@@ -614,8 +587,8 @@
}
EVP_PKEY* key = NULL;
- X509 *cert = NULL;
- STACK_OF(X509) *ca_certs = NULL;
+ X509* cert = NULL;
+ STACK_OF(X509)* ca_certs = NULL;
int status = PKCS12_parse(p12.get(), password, &key, &cert, &ca_certs);
if (status == 0) {
return NULL;
@@ -629,8 +602,8 @@
static EVP_PKEY* GetPrivateKey(BIO* bio, const char* password) {
- EVP_PKEY *key = PEM_read_bio_PrivateKey(
- bio, NULL, PasswordCallback, const_cast<char*>(password));
+ EVP_PKEY* key = PEM_read_bio_PrivateKey(bio, NULL, PasswordCallback,
+ const_cast<char*>(password));
if (key == NULL) {
// We try reading data as PKCS12 only if reading as PEM was unsuccessful and
// if there is no indication that the data is malformed PEM. We assume the
@@ -658,13 +631,13 @@
ThrowIfError(Dart_StringToCString(password_object, &password));
if (strlen(password) > PEM_BUFSIZE - 1) {
Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Password length is greater than 1023 (PEM_BUFSIZE)"));
+ "Password length is greater than 1023 (PEM_BUFSIZE)"));
}
} else if (Dart_IsNull(password_object)) {
password = "";
} else {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Password is not a String or null"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Password is not a String or null"));
}
return password;
}
@@ -678,7 +651,7 @@
int status;
{
ScopedMemBIO bio(ThrowIfError(Dart_GetNativeArgument(args, 1)));
- EVP_PKEY *key = GetPrivateKey(bio.bio(), password);
+ EVP_PKEY* key = GetPrivateKey(bio.bio(), password);
status = SSL_CTX_use_PrivateKey(context->context(), key);
// SSL_CTX_use_PrivateKey increments the reference count of key on success,
// so we have to call EVP_PKEY_free on both success and failure.
@@ -701,8 +674,8 @@
}
EVP_PKEY* key = NULL;
- X509 *cert = NULL;
- STACK_OF(X509) *ca_certs = NULL;
+ X509* cert = NULL;
+ STACK_OF(X509)* ca_certs = NULL;
int status = PKCS12_parse(p12.get(), password, &key, &cert, &ca_certs);
if (status == 0) {
return status;
@@ -779,12 +752,10 @@
int status;
{
ScopedMemBIO bio(ThrowIfError(Dart_GetNativeArgument(args, 1)));
- status = SetTrustedCertificatesBytes(
- context->context(), bio.bio(), password);
+ status =
+ SetTrustedCertificatesBytes(context->context(), bio.bio(), password);
}
- CheckStatus(status,
- "TlsException",
- "Failure in setTrustedCertificatesBytes");
+ CheckStatus(status, "TlsException", "Failure in setTrustedCertificatesBytes");
}
@@ -914,8 +885,8 @@
}
EVP_PKEY* key = NULL;
- X509 *cert = NULL;
- STACK_OF(X509) *ca_certs = NULL;
+ X509* cert = NULL;
+ STACK_OF(X509)* ca_certs = NULL;
int status = PKCS12_parse(p12.get(), password, &key, &cert, &ca_certs);
if (status == 0) {
return status;
@@ -1010,9 +981,7 @@
ScopedMemBIO bio(ThrowIfError(Dart_GetNativeArgument(args, 1)));
status = UseChainBytes(context->context(), bio.bio(), password);
}
- CheckStatus(status,
- "TlsException",
- "Failure in useCertificateChainBytes");
+ CheckStatus(status, "TlsException", "Failure in useCertificateChainBytes");
}
@@ -1025,8 +994,8 @@
}
EVP_PKEY* key = NULL;
- X509 *cert = NULL;
- STACK_OF(X509) *ca_certs = NULL;
+ X509* cert = NULL;
+ STACK_OF(X509)* ca_certs = NULL;
int status = PKCS12_parse(p12.get(), password, &key, &cert, &ca_certs);
if (status == 0) {
return status;
@@ -1097,19 +1066,15 @@
status = SetClientAuthorities(context->context(), bio.bio(), password);
}
- CheckStatus(status,
- "TlsException",
- "Failure in setClientAuthoritiesBytes");
+ CheckStatus(status, "TlsException", "Failure in setClientAuthoritiesBytes");
}
void FUNCTION_NAME(SecurityContext_SetAlpnProtocols)(
Dart_NativeArguments args) {
SSLContext* context = GetSecurityContext(args);
- Dart_Handle protocols_handle =
- ThrowIfError(Dart_GetNativeArgument(args, 1));
- Dart_Handle is_server_handle =
- ThrowIfError(Dart_GetNativeArgument(args, 2));
+ Dart_Handle protocols_handle = ThrowIfError(Dart_GetNativeArgument(args, 1));
+ Dart_Handle is_server_handle = ThrowIfError(Dart_GetNativeArgument(args, 2));
if (Dart_IsBoolean(is_server_handle)) {
bool is_server = DartUtils::GetBooleanValue(is_server_handle);
SetAlpnProtocolList(protocols_handle, NULL, context, is_server);
@@ -1120,8 +1085,7 @@
}
-void FUNCTION_NAME(X509_Subject)(
- Dart_NativeArguments args) {
+void FUNCTION_NAME(X509_Subject)(Dart_NativeArguments args) {
X509* certificate = GetX509Certificate(args);
X509_NAME* subject = X509_get_subject_name(certificate);
char* subject_string = X509_NAME_oneline(subject, NULL, 0);
@@ -1130,8 +1094,7 @@
}
-void FUNCTION_NAME(X509_Issuer)(
- Dart_NativeArguments args) {
+void FUNCTION_NAME(X509_Issuer)(Dart_NativeArguments args) {
X509* certificate = GetX509Certificate(args);
X509_NAME* issuer = X509_get_issuer_name(certificate);
char* issuer_string = X509_NAME_oneline(issuer, NULL, 0);
@@ -1153,16 +1116,14 @@
return Dart_NewInteger((86400LL * days + seconds) * 1000LL);
}
-void FUNCTION_NAME(X509_StartValidity)(
- Dart_NativeArguments args) {
+void FUNCTION_NAME(X509_StartValidity)(Dart_NativeArguments args) {
X509* certificate = GetX509Certificate(args);
ASN1_TIME* not_before = X509_get_notBefore(certificate);
Dart_SetReturnValue(args, ASN1TimeToMilliseconds(not_before));
}
-void FUNCTION_NAME(X509_EndValidity)(
- Dart_NativeArguments args) {
+void FUNCTION_NAME(X509_EndValidity)(Dart_NativeArguments args) {
X509* certificate = GetX509Certificate(args);
ASN1_TIME* not_after = X509_get_notAfter(certificate);
Dart_SetReturnValue(args, ASN1TimeToMilliseconds(not_after));
@@ -1204,8 +1165,8 @@
}
if (filter->ProcessAllBuffers(starts, ends, in_handshake)) {
- CObjectArray* result = new CObjectArray(
- CObject::NewArray(SSLFilter::kNumBuffers * 2));
+ CObjectArray* result =
+ new CObjectArray(CObject::NewArray(SSLFilter::kNumBuffers * 2));
for (int i = 0; i < SSLFilter::kNumBuffers; ++i) {
result->SetAt(2 * i, new CObjectInt32(CObject::NewInt32(starts[i])));
result->SetAt(2 * i + 1, new CObjectInt32(CObject::NewInt32(ends[i])));
@@ -1245,18 +1206,18 @@
// Then, since the last free byte is at position start - 2,
// the interval is [end, size - 1).
int buffer_end = (start == 0) ? size - 1 : size;
- int bytes = (i == kReadPlaintext) ?
- ProcessReadPlaintextBuffer(end, buffer_end) :
- ProcessWriteEncryptedBuffer(end, buffer_end);
+ int bytes = (i == kReadPlaintext)
+ ? ProcessReadPlaintextBuffer(end, buffer_end)
+ : ProcessWriteEncryptedBuffer(end, buffer_end);
if (bytes < 0) return false;
end += bytes;
ASSERT(end <= size);
if (end == size) end = 0;
}
if (start > end + 1) {
- int bytes = (i == kReadPlaintext) ?
- ProcessReadPlaintextBuffer(end, start - 1) :
- ProcessWriteEncryptedBuffer(end, start - 1);
+ int bytes = (i == kReadPlaintext)
+ ? ProcessReadPlaintextBuffer(end, start - 1)
+ : ProcessWriteEncryptedBuffer(end, start - 1);
if (bytes < 0) return false;
end += bytes;
ASSERT(end < start);
@@ -1270,18 +1231,18 @@
if (end < start) {
// Data may be split into two segments. In this case,
// the first is [start, size).
- int bytes = (i == kReadEncrypted) ?
- ProcessReadEncryptedBuffer(start, size) :
- ProcessWritePlaintextBuffer(start, size);
+ int bytes = (i == kReadEncrypted)
+ ? ProcessReadEncryptedBuffer(start, size)
+ : ProcessWritePlaintextBuffer(start, size);
if (bytes < 0) return false;
start += bytes;
ASSERT(start <= size);
if (start == size) start = 0;
}
if (start < end) {
- int bytes = (i == kReadEncrypted) ?
- ProcessReadEncryptedBuffer(start, end) :
- ProcessWritePlaintextBuffer(start, end);
+ int bytes = (i == kReadEncrypted)
+ ? ProcessReadEncryptedBuffer(start, end)
+ : ProcessWritePlaintextBuffer(start, end);
if (bytes < 0) return false;
start += bytes;
ASSERT(start <= end);
@@ -1325,8 +1286,8 @@
RETURN_IF_ERROR(secure_filter_impl_type);
Dart_Handle size_string = DartUtils::NewString("SIZE");
RETURN_IF_ERROR(size_string);
- Dart_Handle dart_buffer_size = Dart_GetField(
- secure_filter_impl_type, size_string);
+ Dart_Handle dart_buffer_size =
+ Dart_GetField(secure_filter_impl_type, size_string);
RETURN_IF_ERROR(dart_buffer_size);
int64_t buffer_size = 0;
@@ -1336,8 +1297,8 @@
Dart_Handle encrypted_size_string = DartUtils::NewString("ENCRYPTED_SIZE");
RETURN_IF_ERROR(encrypted_size_string);
- Dart_Handle dart_encrypted_buffer_size = Dart_GetField(
- secure_filter_impl_type, encrypted_size_string);
+ Dart_Handle dart_encrypted_buffer_size =
+ Dart_GetField(secure_filter_impl_type, encrypted_size_string);
RETURN_IF_ERROR(dart_encrypted_buffer_size);
int64_t encrypted_buffer_size = 0;
@@ -1429,12 +1390,12 @@
}
-int AlpnCallback(SSL *ssl,
- const uint8_t **out,
- uint8_t *outlen,
- const uint8_t *in,
+int AlpnCallback(SSL* ssl,
+ const uint8_t** out,
+ uint8_t* outlen,
+ const uint8_t* in,
unsigned int inlen,
- void *arg) {
+ void* arg) {
// 'in' and 'arg' are sequences of (length, data) strings with 1-byte lengths.
// 'arg' is 0-terminated. Finds the first string in 'arg' that is in 'in'.
uint8_t* server_list = static_cast<uint8_t*>(arg);
@@ -1473,10 +1434,8 @@
int status;
Dart_Handle result = Dart_TypedDataAcquireData(
- protocols_handle,
- &protocols_type,
- reinterpret_cast<void**>(&protocol_string),
- &protocol_string_len);
+ protocols_handle, &protocols_type,
+ reinterpret_cast<void**>(&protocol_string), &protocol_string_len);
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
@@ -1499,8 +1458,8 @@
static_cast<uint8_t*>(malloc(protocol_string_len + 1));
memmove(protocol_string_copy, protocol_string, protocol_string_len);
protocol_string_copy[protocol_string_len] = '\0';
- SSL_CTX_set_alpn_select_cb(
- context->context(), AlpnCallback, protocol_string_copy);
+ SSL_CTX_set_alpn_select_cb(context->context(), AlpnCallback,
+ protocol_string_copy);
context->set_alpn_protocol_string(protocol_string_copy);
} else {
// The function makes a local copy of protocol_string, which it owns.
@@ -1510,8 +1469,8 @@
} else {
ASSERT(context != NULL);
ASSERT(ssl == NULL);
- status = SSL_CTX_set_alpn_protos(
- context->context(), protocol_string, protocol_string_len);
+ status = SSL_CTX_set_alpn_protos(context->context(), protocol_string,
+ protocol_string_len);
}
ASSERT(status == 0); // The function returns a non-standard status.
}
@@ -1545,7 +1504,7 @@
if (is_server_) {
int certificate_mode =
- request_client_certificate ? SSL_VERIFY_PEER : SSL_VERIFY_NONE;
+ request_client_certificate ? SSL_VERIFY_PEER : SSL_VERIFY_NONE;
if (require_client_certificate) {
certificate_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
}
@@ -1558,9 +1517,9 @@
// against the certificate presented by the server.
X509_VERIFY_PARAM* certificate_checking_parameters = SSL_get0_param(ssl_);
hostname_ = strdup(hostname);
- X509_VERIFY_PARAM_set_flags(certificate_checking_parameters,
- X509_V_FLAG_PARTIAL_CHAIN |
- X509_V_FLAG_TRUSTED_FIRST);
+ X509_VERIFY_PARAM_set_flags(
+ certificate_checking_parameters,
+ X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_TRUSTED_FIRST);
X509_VERIFY_PARAM_set_hostflags(certificate_checking_parameters, 0);
status = X509_VERIFY_PARAM_set1_host(certificate_checking_parameters,
hostname_, strlen(hostname_));
@@ -1597,7 +1556,7 @@
}
-int printErrorCallback(const char *str, size_t len, void *ctx) {
+int printErrorCallback(const char* str, size_t len, void* ctx) {
Log::PrintErr("%.*s\n", static_cast<int>(len), str);
return 1;
}
@@ -1617,9 +1576,9 @@
in_handshake_ = true;
return;
}
- CheckStatus(status,
- "HandshakeException",
- is_server_ ? "Handshake error in server" : "Handshake error in client");
+ CheckStatus(status, "HandshakeException", is_server_
+ ? "Handshake error in server"
+ : "Handshake error in client");
// Handshake succeeded.
if (in_handshake_) {
// TODO(24071): Check return value of SSL_get_verify_result, this
@@ -1721,8 +1680,7 @@
int bytes_processed = 0;
if (length > 0) {
bytes_processed = SSL_read(
- ssl_,
- reinterpret_cast<char*>((buffers_[kReadPlaintext] + start)),
+ ssl_, reinterpret_cast<char*>((buffers_[kReadPlaintext] + start)),
length);
if (bytes_processed < 0) {
int error = SSL_get_error(ssl_, bytes_processed);
@@ -1736,8 +1694,8 @@
int SSLFilter::ProcessWritePlaintextBuffer(int start, int end) {
int length = end - start;
- int bytes_processed = SSL_write(
- ssl_, buffers_[kWritePlaintext] + start, length);
+ int bytes_processed =
+ SSL_write(ssl_, buffers_[kWritePlaintext] + start, length);
if (bytes_processed < 0) {
if (SSL_LOG_DATA) {
Log::Print("SSL_write returned error %d\n", bytes_processed);
@@ -1751,8 +1709,8 @@
/* Read encrypted data from the circular buffer to the filter */
int SSLFilter::ProcessReadEncryptedBuffer(int start, int end) {
int length = end - start;
- if (SSL_LOG_DATA) Log::Print(
- "Entering ProcessReadEncryptedBuffer with %d bytes\n", length);
+ if (SSL_LOG_DATA)
+ Log::Print("Entering ProcessReadEncryptedBuffer with %d bytes\n", length);
int bytes_processed = 0;
if (length > 0) {
bytes_processed =
@@ -1760,14 +1718,15 @@
if (bytes_processed <= 0) {
bool retry = BIO_should_retry(socket_side_);
if (!retry) {
- if (SSL_LOG_DATA) Log::Print(
- "BIO_write failed in ReadEncryptedBuffer\n");
+ if (SSL_LOG_DATA)
+ Log::Print("BIO_write failed in ReadEncryptedBuffer\n");
}
bytes_processed = 0;
}
}
- if (SSL_LOG_DATA) Log::Print(
- "Leaving ProcessReadEncryptedBuffer wrote %d bytes\n", bytes_processed);
+ if (SSL_LOG_DATA)
+ Log::Print("Leaving ProcessReadEncryptedBuffer wrote %d bytes\n",
+ bytes_processed);
return bytes_processed;
}
@@ -1776,16 +1735,17 @@
int length = end - start;
int bytes_processed = 0;
if (length > 0) {
- bytes_processed = BIO_read(socket_side_,
- buffers_[kWriteEncrypted] + start,
- length);
+ bytes_processed =
+ BIO_read(socket_side_, buffers_[kWriteEncrypted] + start, length);
if (bytes_processed < 0) {
- if (SSL_LOG_DATA) Log::Print(
- "WriteEncrypted BIO_read returned error %d\n", bytes_processed);
+ if (SSL_LOG_DATA)
+ Log::Print("WriteEncrypted BIO_read returned error %d\n",
+ bytes_processed);
return 0;
} else {
- if (SSL_LOG_DATA) Log::Print(
- "WriteEncrypted BIO_read wrote %d bytes\n", bytes_processed);
+ if (SSL_LOG_DATA)
+ Log::Print("WriteEncrypted BIO_read wrote %d bytes\n",
+ bytes_processed);
}
}
return bytes_processed;
diff --git a/runtime/bin/secure_socket_boringssl.h b/runtime/bin/secure_socket_boringssl.h
index fe7bd8d..a24194a 100644
--- a/runtime/bin/secure_socket_boringssl.h
+++ b/runtime/bin/secure_socket_boringssl.h
@@ -35,10 +35,8 @@
class SSLContext {
public:
- explicit SSLContext(SSL_CTX* context) :
- context_(context),
- alpn_protocol_string_(NULL) {
- }
+ explicit SSLContext(SSL_CTX* context)
+ : context_(context), alpn_protocol_string_(NULL) {}
~SSLContext() {
SSL_CTX_free(context_);
@@ -92,7 +90,7 @@
handshake_complete_(NULL),
bad_certificate_callback_(NULL),
in_handshake_(false),
- hostname_(NULL) { }
+ hostname_(NULL) {}
~SSLFilter();
diff --git a/runtime/bin/secure_socket_ios.cc b/runtime/bin/secure_socket_ios.cc
index a92c45b..0f19380 100644
--- a/runtime/bin/secure_socket_ios.cc
+++ b/runtime/bin/secure_socket_ios.cc
@@ -74,7 +74,7 @@
const char* message) {
TextBuffer status_message(SSL_ERROR_MESSAGE_BUFFER_SIZE);
status_message.Printf("OSStatus = %ld: https://www.osstatus.com",
- static_cast<intptr_t>(status));
+ static_cast<intptr_t>(status));
OSError os_error_struct(status, status_message.buf(), OSError::kBoringSSL);
Dart_Handle os_error = DartUtils::NewDartOSError(&os_error_struct);
Dart_Handle exception =
@@ -99,10 +99,9 @@
SSLFilter* filter;
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
ASSERT(Dart_IsInstance(dart_this));
- ThrowIfError(Dart_GetNativeInstanceField(
- dart_this,
- kSSLFilterNativeFieldIndex,
- reinterpret_cast<intptr_t*>(&filter)));
+ ThrowIfError(
+ Dart_GetNativeInstanceField(dart_this, kSSLFilterNativeFieldIndex,
+ reinterpret_cast<intptr_t*>(&filter)));
return filter;
}
@@ -121,15 +120,12 @@
Dart_Handle dart_this = Dart_GetNativeArgument(args, 0);
RETURN_IF_ERROR(dart_this);
ASSERT(Dart_IsInstance(dart_this));
- Dart_Handle err = Dart_SetNativeInstanceField(
- dart_this,
- kSSLFilterNativeFieldIndex,
- reinterpret_cast<intptr_t>(filter));
+ Dart_Handle err =
+ Dart_SetNativeInstanceField(dart_this, kSSLFilterNativeFieldIndex,
+ reinterpret_cast<intptr_t>(filter));
RETURN_IF_ERROR(err);
- Dart_NewWeakPersistentHandle(dart_this,
- reinterpret_cast<void*>(filter),
- approximate_size_of_filter,
- DeleteFilter);
+ Dart_NewWeakPersistentHandle(dart_this, reinterpret_cast<void*>(filter),
+ approximate_size_of_filter, DeleteFilter);
return Dart_Null();
}
@@ -138,10 +134,9 @@
SSLCertContext* context;
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
ASSERT(Dart_IsInstance(dart_this));
- ThrowIfError(Dart_GetNativeInstanceField(
- dart_this,
- kSecurityContextNativeFieldIndex,
- reinterpret_cast<intptr_t*>(&context)));
+ ThrowIfError(
+ Dart_GetNativeInstanceField(dart_this, kSecurityContextNativeFieldIndex,
+ reinterpret_cast<intptr_t*>(&context)));
return context;
}
@@ -160,14 +155,11 @@
Dart_Handle dart_this = Dart_GetNativeArgument(args, 0);
RETURN_IF_ERROR(dart_this);
ASSERT(Dart_IsInstance(dart_this));
- Dart_Handle err = Dart_SetNativeInstanceField(
- dart_this,
- kSecurityContextNativeFieldIndex,
- reinterpret_cast<intptr_t>(context));
+ Dart_Handle err =
+ Dart_SetNativeInstanceField(dart_this, kSecurityContextNativeFieldIndex,
+ reinterpret_cast<intptr_t>(context));
RETURN_IF_ERROR(err);
- Dart_NewWeakPersistentHandle(dart_this,
- context,
- approximate_size_of_context,
+ Dart_NewWeakPersistentHandle(dart_this, context, approximate_size_of_context,
DeleteCertContext);
return Dart_Null();
}
@@ -177,10 +169,9 @@
SecCertificateRef certificate;
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
ASSERT(Dart_IsInstance(dart_this));
- ThrowIfError(Dart_GetNativeInstanceField(
- dart_this,
- kX509NativeFieldIndex,
- reinterpret_cast<intptr_t*>(&certificate)));
+ ThrowIfError(
+ Dart_GetNativeInstanceField(dart_this, kX509NativeFieldIndex,
+ reinterpret_cast<intptr_t*>(&certificate)));
return certificate;
}
@@ -203,7 +194,7 @@
if (Dart_IsError(x509_type)) {
return x509_type;
}
- Dart_Handle arguments[] = { NULL };
+ Dart_Handle arguments[] = {NULL};
Dart_Handle result =
Dart_New(x509_type, DartUtils::NewString("_"), 0, arguments);
@@ -215,15 +206,12 @@
// CFRetain in case the returned Dart object outlives the SecurityContext.
// CFRelease is in the Dart object's finalizer
CFRetain(certificate);
- Dart_NewWeakPersistentHandle(result,
- reinterpret_cast<void*>(certificate),
+ Dart_NewWeakPersistentHandle(result, reinterpret_cast<void*>(certificate),
approximate_size_of_certificate,
ReleaseCertificate);
Dart_Handle status = Dart_SetNativeInstanceField(
- result,
- kX509NativeFieldIndex,
- reinterpret_cast<intptr_t>(certificate));
+ result, kX509NativeFieldIndex, reinterpret_cast<intptr_t>(certificate));
if (Dart_IsError(status)) {
return status;
}
@@ -245,8 +233,8 @@
} else if (Dart_IsNull(password_object)) {
password = "";
} else {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Password is not a String or null"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Password is not a String or null"));
}
return password;
}
@@ -256,8 +244,8 @@
CFStringRef password,
CFArrayRef* out_certs,
SecIdentityRef* out_identity) {
- const void* keys[] = { kSecImportExportPassphrase };
- const void* values[] = { password };
+ const void* keys[] = {kSecImportExportPassphrase};
+ const void* values[] = {password};
CFDictionaryRef params =
CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef items = NULL;
@@ -267,7 +255,7 @@
if (status != noErr) {
if (SSL_LOG_STATUS) {
Log::PrintErr("SecPKCS12Import: status = %ld",
- static_cast<intptr_t>(status));
+ static_cast<intptr_t>(status));
return status;
}
}
@@ -328,8 +316,8 @@
CFIndex count = CFArrayGetCount(certs);
Log::PrintErr("\titem %ld has a cert chain %ld certs long\n", i, count);
}
- CFArrayAppendArray(
- result_certs, certs, CFRangeMake(0, CFArrayGetCount(certs)));
+ CFArrayAppendArray(result_certs, certs,
+ CFRangeMake(0, CFArrayGetCount(certs)));
}
}
@@ -365,8 +353,8 @@
ASSERT(password != NULL);
OSStatus status = noErr;
- CFDataRef cfdata = CFDataCreateWithBytesNoCopy(
- NULL, buffer, length, kCFAllocatorNull);
+ CFDataRef cfdata =
+ CFDataCreateWithBytesNoCopy(NULL, buffer, length, kCFAllocatorNull);
CFStringRef cfpassword = CFStringCreateWithCStringNoCopy(
NULL, password, kCFStringEncodingUTF8, kCFAllocatorNull);
ASSERT(cfdata != NULL);
@@ -415,15 +403,11 @@
SSLCertContext* context = NULL;
if (!Dart_IsNull(context_object)) {
ThrowIfError(Dart_GetNativeInstanceField(
- context_object,
- kSecurityContextNativeFieldIndex,
+ context_object, kSecurityContextNativeFieldIndex,
reinterpret_cast<intptr_t*>(&context)));
}
- GetFilter(args)->Connect(dart_this,
- host_name,
- context,
- is_server,
+ GetFilter(args)->Connect(dart_this, host_name, context, is_server,
request_client_certificate,
require_client_certificate);
}
@@ -460,8 +444,7 @@
DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 2));
bool require_client_certificate =
DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 3));
- GetFilter(args)->Renegotiate(use_session_cache,
- request_client_certificate,
+ GetFilter(args)->Renegotiate(use_session_cache, request_client_certificate,
require_client_certificate);
}
@@ -480,8 +463,7 @@
void FUNCTION_NAME(SecureSocket_RegisterBadCertificateCallback)(
Dart_NativeArguments args) {
- Dart_Handle callback =
- ThrowIfError(Dart_GetNativeArgument(args, 1));
+ Dart_Handle callback = ThrowIfError(Dart_GetNativeArgument(args, 1));
if (!Dart_IsClosure(callback) && !Dart_IsNull(callback)) {
Dart_ThrowException(DartUtils::NewDartArgumentError(
"Illegal argument to RegisterBadCertificateCallback"));
@@ -526,8 +508,8 @@
SecIdentityRef identity = NULL;
{
ScopedMemBuffer buffer(ThrowIfError(Dart_GetNativeArgument(args, 1)));
- status = ExtractSecItems(
- buffer.get(), buffer.length(), password, &cert_chain, &identity);
+ status = ExtractSecItems(buffer.get(), buffer.length(), password,
+ &cert_chain, &identity);
}
// Set the context fields. Repeated calls to usePrivateKeyBytes are an error.
@@ -642,7 +624,7 @@
void FUNCTION_NAME(X509_EndValidity)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartUnsupportedError(
+ Dart_ThrowException(DartUtils::NewDartUnsupportedError(
"X509Certificate.endValidity is not supported on this platform."));
}
@@ -681,8 +663,8 @@
OSStatus status = filter->ProcessAllBuffers(starts, ends, in_handshake);
if (status == noErr) {
- CObjectArray* result = new CObjectArray(
- CObject::NewArray(SSLFilter::kNumBuffers * 2));
+ CObjectArray* result =
+ new CObjectArray(CObject::NewArray(SSLFilter::kNumBuffers * 2));
for (intptr_t i = 0; i < SSLFilter::kNumBuffers; ++i) {
result->SetAt(2 * i, new CObjectInt32(CObject::NewInt32(starts[i])));
result->SetAt(2 * i + 1, new CObjectInt32(CObject::NewInt32(ends[i])));
@@ -691,11 +673,11 @@
} else {
TextBuffer status_message(SSL_ERROR_MESSAGE_BUFFER_SIZE);
status_message.Printf("OSStatus = %ld: https://www.osstatus.com",
- static_cast<intptr_t>(status));
+ static_cast<intptr_t>(status));
CObjectArray* result = new CObjectArray(CObject::NewArray(2));
result->SetAt(0, new CObjectInt32(CObject::NewInt32(status)));
- result->SetAt(1, new CObjectString(CObject::NewString(
- status_message.buf())));
+ result->SetAt(1,
+ new CObjectString(CObject::NewString(status_message.buf())));
return result;
}
}
@@ -741,8 +723,8 @@
}
Dart_Handle buffer_handle =
ThrowIfError(Dart_HandleFromPersistent(dart_buffer_objects_[idx]));
- ThrowIfError(DartUtils::SetIntegerField(
- buffer_handle, "start", static_cast<int64_t>(value)));
+ ThrowIfError(DartUtils::SetIntegerField(buffer_handle, "start",
+ static_cast<int64_t>(value)));
}
@@ -753,8 +735,8 @@
}
Dart_Handle buffer_handle =
ThrowIfError(Dart_HandleFromPersistent(dart_buffer_objects_[idx]));
- ThrowIfError(DartUtils::SetIntegerField(
- buffer_handle, "end", static_cast<int64_t>(value)));
+ ThrowIfError(DartUtils::SetIntegerField(buffer_handle, "end",
+ static_cast<int64_t>(value)));
}
@@ -888,8 +870,8 @@
RETURN_IF_ERROR(secure_filter_impl_type);
Dart_Handle size_string = DartUtils::NewString("SIZE");
RETURN_IF_ERROR(size_string);
- Dart_Handle dart_buffer_size = Dart_GetField(
- secure_filter_impl_type, size_string);
+ Dart_Handle dart_buffer_size =
+ Dart_GetField(secure_filter_impl_type, size_string);
RETURN_IF_ERROR(dart_buffer_size);
int64_t buffer_size = 0;
@@ -899,8 +881,8 @@
Dart_Handle encrypted_size_string = DartUtils::NewString("ENCRYPTED_SIZE");
RETURN_IF_ERROR(encrypted_size_string);
- Dart_Handle dart_encrypted_buffer_size = Dart_GetField(
- secure_filter_impl_type, encrypted_size_string);
+ Dart_Handle dart_encrypted_buffer_size =
+ Dart_GetField(secure_filter_impl_type, encrypted_size_string);
RETURN_IF_ERROR(dart_encrypted_buffer_size);
int64_t encrypted_buffer_size = 0;
@@ -1008,34 +990,25 @@
// Configure the context.
OSStatus status;
status = SSLSetPeerDomainName(ssl_context, hostname, strlen(hostname));
- CheckStatus(status,
- "TlsException",
- "Failed to set peer domain name");
+ CheckStatus(status, "TlsException", "Failed to set peer domain name");
- status = SSLSetIOFuncs(
- ssl_context, SSLFilter::SSLReadCallback, SSLFilter::SSLWriteCallback);
- CheckStatus(status,
- "TlsException",
- "Failed to set IO Callbacks");
+ status = SSLSetIOFuncs(ssl_context, SSLFilter::SSLReadCallback,
+ SSLFilter::SSLWriteCallback);
+ CheckStatus(status, "TlsException", "Failed to set IO Callbacks");
- status = SSLSetConnection(
- ssl_context, reinterpret_cast<SSLConnectionRef>(this));
- CheckStatus(status,
- "TlsException",
- "Failed to set connection object");
+ status =
+ SSLSetConnection(ssl_context, reinterpret_cast<SSLConnectionRef>(this));
+ CheckStatus(status, "TlsException", "Failed to set connection object");
// Always evaluate the certs manually so that we can cache the peer
// certificates in the context for calls to peerCertificate.
- status = SSLSetSessionOption(
- ssl_context, kSSLSessionOptionBreakOnServerAuth, true);
- CheckStatus(status,
- "TlsException",
- "Failed to set BreakOnServerAuth option");
+ status = SSLSetSessionOption(ssl_context, kSSLSessionOptionBreakOnServerAuth,
+ true);
+ CheckStatus(status, "TlsException", "Failed to set BreakOnServerAuth option");
status = SSLSetProtocolVersionMin(ssl_context, kTLSProtocol1);
- CheckStatus(status,
- "TlsException",
- "Failed to set minimum protocol version to kTLSProtocol1");
+ CheckStatus(status, "TlsException",
+ "Failed to set minimum protocol version to kTLSProtocol1");
// If the context has an identity pass it to SSLSetCertificate().
if (context->identity() != NULL) {
@@ -1048,8 +1021,8 @@
// Skip the first one, it's already included in the identity.
CFIndex chain_length = CFArrayGetCount(context->cert_chain());
if (chain_length > 1) {
- CFArrayAppendArray(
- chain, context->cert_chain(), CFRangeMake(1, chain_length));
+ CFArrayAppendArray(chain, context->cert_chain(),
+ CFRangeMake(1, chain_length));
}
}
@@ -1061,21 +1034,20 @@
if (is_server) {
SSLAuthenticate auth =
require_client_certificate
- ? kAlwaysAuthenticate
- : (request_client_certificate ? kTryAuthenticate : kNeverAuthenticate);
+ ? kAlwaysAuthenticate
+ : (request_client_certificate ? kTryAuthenticate
+ : kNeverAuthenticate);
status = SSLSetClientSideAuthenticate(ssl_context, auth);
- CheckStatus(status,
- "TlsException",
- "Failed to set client authentication mode");
+ CheckStatus(status, "TlsException",
+ "Failed to set client authentication mode");
// If we're at least trying client authentication, then break handshake
// for client authentication.
if (auth != kNeverAuthenticate) {
- status = SSLSetSessionOption(
- ssl_context, kSSLSessionOptionBreakOnClientAuth, true);
- CheckStatus(status,
- "TlsException",
- "Failed to set client authentication mode");
+ status = SSLSetSessionOption(ssl_context,
+ kSSLSessionOptionBreakOnClientAuth, true);
+ CheckStatus(status, "TlsException",
+ "Failed to set client authentication mode");
}
}
@@ -1092,9 +1064,9 @@
status = noErr;
in_handshake_ = true;
}
- CheckStatus(status,
- "HandshakeException",
- is_server_ ? "Handshake error in server" : "Handshake error in client");
+ CheckStatus(status, "HandshakeException", is_server_
+ ? "Handshake error in server"
+ : "Handshake error in client");
}
@@ -1113,7 +1085,7 @@
}
if (SSL_LOG_STATUS) {
Log::PrintErr("Handshake error from SSLCopyPeerTrust(): %ld.\n",
- static_cast<intptr_t>(status));
+ static_cast<intptr_t>(status));
}
return status;
}
@@ -1130,7 +1102,7 @@
if (status != noErr) {
if (SSL_LOG_STATUS) {
Log::PrintErr("Handshake error from SecTrustSetAnchorCertificates: %ld\n",
- static_cast<intptr_t>(status));
+ static_cast<intptr_t>(status));
}
CFRelease(trusted_certs);
CFRelease(peer_trust);
@@ -1138,7 +1110,8 @@
}
if (SSL_LOG_STATUS) {
- Log::PrintErr("Handshake %s built in root certs\n",
+ Log::PrintErr(
+ "Handshake %s built in root certs\n",
cert_context_.get()->trust_builtin() ? "trusting" : "not trusting");
}
@@ -1350,7 +1323,8 @@
OSStatus SSLFilter::SSLReadCallback(SSLConnectionRef connection,
- void* data, size_t* data_requested) {
+ void* data,
+ size_t* data_requested) {
// Copy at most `data_requested` bytes from `buffers_[kReadEncrypted]` into
// `data`
ASSERT(connection != NULL);
@@ -1396,7 +1370,7 @@
if (SSL_LOG_DATA) {
Log::PrintErr("SSLReadCallback: requested: %ld, read %ld bytes\n",
- *data_requested, data_read);
+ *data_requested, data_read);
}
filter->SetBufferStart(kReadEncrypted, start);
@@ -1415,11 +1389,10 @@
OSStatus status = noErr;
size_t bytes = 0;
if (length > 0) {
- status = SSLRead(
- ssl_context_,
- reinterpret_cast<void*>((buffers_[kReadPlaintext] + start)),
- length,
- &bytes);
+ status =
+ SSLRead(ssl_context_,
+ reinterpret_cast<void*>((buffers_[kReadPlaintext] + start)),
+ length, &bytes);
if (SSL_LOG_STATUS) {
Log::PrintErr("SSLRead: status = %ld\n", static_cast<intptr_t>(status));
}
@@ -1430,8 +1403,8 @@
}
if (SSL_LOG_DATA) {
Log::PrintErr(
- "ProcessReadPlaintextBuffer: requested: %ld, read %ld bytes\n",
- length, bytes);
+ "ProcessReadPlaintextBuffer: requested: %ld, read %ld bytes\n", length,
+ bytes);
}
*bytes_processed = static_cast<intptr_t>(bytes);
return status;
@@ -1439,7 +1412,8 @@
OSStatus SSLFilter::SSLWriteCallback(SSLConnectionRef connection,
- const void* data, size_t* data_provided) {
+ const void* data,
+ size_t* data_provided) {
// Copy at most `data_provided` bytes from data into
// `buffers_[kWriteEncrypted]`.
ASSERT(connection != NULL);
@@ -1447,7 +1421,7 @@
ASSERT(data_provided != NULL);
SSLFilter* filter =
- const_cast<SSLFilter*>(reinterpret_cast<const SSLFilter*>(connection));
+ const_cast<SSLFilter*>(reinterpret_cast<const SSLFilter*>(connection));
const uint8_t* datap = reinterpret_cast<const uint8_t*>(data);
uint8_t* buffer = filter->buffers_[kWriteEncrypted];
intptr_t start = filter->GetBufferStart(kWriteEncrypted);
@@ -1488,7 +1462,7 @@
if (SSL_LOG_DATA) {
Log::PrintErr("SSLWriteCallback: provided: %ld, written %ld bytes\n",
- *data_provided, data_written);
+ *data_provided, data_written);
}
filter->SetBufferEnd(kWriteEncrypted, end);
@@ -1505,11 +1479,10 @@
OSStatus status = noErr;
size_t bytes = 0;
if (length > 0) {
- status = SSLWrite(
- ssl_context_,
- reinterpret_cast<void*>(buffers_[kWritePlaintext] + start),
- length,
- &bytes);
+ status =
+ SSLWrite(ssl_context_,
+ reinterpret_cast<void*>(buffers_[kWritePlaintext] + start),
+ length, &bytes);
if (SSL_LOG_STATUS) {
Log::PrintErr("SSLWrite: status = %ld\n", static_cast<intptr_t>(status));
}
@@ -1520,7 +1493,7 @@
}
if (SSL_LOG_DATA) {
Log::PrintErr("ProcessWritePlaintextBuffer: requested: %ld, written: %ld\n",
- length, bytes);
+ length, bytes);
}
*bytes_processed = static_cast<intptr_t>(bytes);
return status;
diff --git a/runtime/bin/secure_socket_ios.h b/runtime/bin/secure_socket_ios.h
index 84e46e1..8a59cb7 100644
--- a/runtime/bin/secure_socket_ios.h
+++ b/runtime/bin/secure_socket_ios.h
@@ -35,13 +35,13 @@
// thread. Setters return false if the field was already set.
class SSLCertContext : public ReferenceCounted<SSLCertContext> {
public:
- SSLCertContext() :
- ReferenceCounted(),
- mutex_(new Mutex()),
- trusted_certs_(NULL),
- identity_(NULL),
- cert_chain_(NULL),
- trust_builtin_(false) {}
+ SSLCertContext()
+ : ReferenceCounted(),
+ mutex_(new Mutex()),
+ trusted_certs_(NULL),
+ identity_(NULL),
+ cert_chain_(NULL),
+ trust_builtin_(false) {}
~SSLCertContext() {
{
@@ -150,8 +150,7 @@
connected_(false),
bad_cert_(false),
is_server_(false),
- hostname_(NULL) {
- }
+ hostname_(NULL) {}
~SSLFilter();
diff --git a/runtime/bin/secure_socket_macos.cc b/runtime/bin/secure_socket_macos.cc
index 6b564df..910008c 100644
--- a/runtime/bin/secure_socket_macos.cc
+++ b/runtime/bin/secure_socket_macos.cc
@@ -86,11 +86,11 @@
CFStringRef error_string = SecCopyErrorMessageString(status, NULL);
if (error_string == NULL) {
status_message.Printf("OSStatus = %ld: https://www.osstatus.com",
- static_cast<intptr_t>(status));
+ static_cast<intptr_t>(status));
} else {
char* error = CFStringRefToCString(error_string);
- status_message.Printf("OSStatus = %ld: %s",
- static_cast<intptr_t>(status), error);
+ status_message.Printf("OSStatus = %ld: %s", static_cast<intptr_t>(status),
+ error);
CFRelease(error_string);
}
OSError os_error_struct(status, status_message.buf(), OSError::kBoringSSL);
@@ -117,10 +117,9 @@
SSLFilter* filter;
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
ASSERT(Dart_IsInstance(dart_this));
- ThrowIfError(Dart_GetNativeInstanceField(
- dart_this,
- kSSLFilterNativeFieldIndex,
- reinterpret_cast<intptr_t*>(&filter)));
+ ThrowIfError(
+ Dart_GetNativeInstanceField(dart_this, kSSLFilterNativeFieldIndex,
+ reinterpret_cast<intptr_t*>(&filter)));
return filter;
}
@@ -139,15 +138,12 @@
Dart_Handle dart_this = Dart_GetNativeArgument(args, 0);
RETURN_IF_ERROR(dart_this);
ASSERT(Dart_IsInstance(dart_this));
- Dart_Handle err = Dart_SetNativeInstanceField(
- dart_this,
- kSSLFilterNativeFieldIndex,
- reinterpret_cast<intptr_t>(filter));
+ Dart_Handle err =
+ Dart_SetNativeInstanceField(dart_this, kSSLFilterNativeFieldIndex,
+ reinterpret_cast<intptr_t>(filter));
RETURN_IF_ERROR(err);
- Dart_NewWeakPersistentHandle(dart_this,
- reinterpret_cast<void*>(filter),
- approximate_size_of_filter,
- DeleteFilter);
+ Dart_NewWeakPersistentHandle(dart_this, reinterpret_cast<void*>(filter),
+ approximate_size_of_filter, DeleteFilter);
return Dart_Null();
}
@@ -156,10 +152,9 @@
SSLCertContext* context;
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
ASSERT(Dart_IsInstance(dart_this));
- ThrowIfError(Dart_GetNativeInstanceField(
- dart_this,
- kSecurityContextNativeFieldIndex,
- reinterpret_cast<intptr_t*>(&context)));
+ ThrowIfError(
+ Dart_GetNativeInstanceField(dart_this, kSecurityContextNativeFieldIndex,
+ reinterpret_cast<intptr_t*>(&context)));
return context;
}
@@ -178,14 +173,11 @@
Dart_Handle dart_this = Dart_GetNativeArgument(args, 0);
RETURN_IF_ERROR(dart_this);
ASSERT(Dart_IsInstance(dart_this));
- Dart_Handle err = Dart_SetNativeInstanceField(
- dart_this,
- kSecurityContextNativeFieldIndex,
- reinterpret_cast<intptr_t>(context));
+ Dart_Handle err =
+ Dart_SetNativeInstanceField(dart_this, kSecurityContextNativeFieldIndex,
+ reinterpret_cast<intptr_t>(context));
RETURN_IF_ERROR(err);
- Dart_NewWeakPersistentHandle(dart_this,
- context,
- approximate_size_of_context,
+ Dart_NewWeakPersistentHandle(dart_this, context, approximate_size_of_context,
DeleteCertContext);
return Dart_Null();
}
@@ -195,10 +187,9 @@
SecCertificateRef certificate;
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
ASSERT(Dart_IsInstance(dart_this));
- ThrowIfError(Dart_GetNativeInstanceField(
- dart_this,
- kX509NativeFieldIndex,
- reinterpret_cast<intptr_t*>(&certificate)));
+ ThrowIfError(
+ Dart_GetNativeInstanceField(dart_this, kX509NativeFieldIndex,
+ reinterpret_cast<intptr_t*>(&certificate)));
return certificate;
}
@@ -221,7 +212,7 @@
if (Dart_IsError(x509_type)) {
return x509_type;
}
- Dart_Handle arguments[] = { NULL };
+ Dart_Handle arguments[] = {NULL};
Dart_Handle result =
Dart_New(x509_type, DartUtils::NewString("_"), 0, arguments);
@@ -233,15 +224,12 @@
// CFRetain in case the returned Dart object outlives the SecurityContext.
// CFRelease is in the Dart object's finalizer
CFRetain(certificate);
- Dart_NewWeakPersistentHandle(result,
- reinterpret_cast<void*>(certificate),
+ Dart_NewWeakPersistentHandle(result, reinterpret_cast<void*>(certificate),
approximate_size_of_certificate,
ReleaseCertificate);
Dart_Handle status = Dart_SetNativeInstanceField(
- result,
- kX509NativeFieldIndex,
- reinterpret_cast<intptr_t>(certificate));
+ result, kX509NativeFieldIndex, reinterpret_cast<intptr_t>(certificate));
if (Dart_IsError(status)) {
return status;
}
@@ -263,8 +251,8 @@
} else if (Dart_IsNull(password_object)) {
password = "";
} else {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Password is not a String or null"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Password is not a String or null"));
}
return password;
}
@@ -358,13 +346,13 @@
params.passphrase = password;
CFArrayRef items = NULL;
- status = SecItemImport(
- cfdata, NULL, &format, &sitem_type, 0, ¶ms, NULL, &items);
+ status = SecItemImport(cfdata, NULL, &format, &sitem_type, 0, ¶ms, NULL,
+ &items);
if (status != noErr) {
if (SSL_LOG_CERTS) {
Log::Print("TrySecItemImport failed with: %ld, type = %d, format = %d\n",
- static_cast<intptr_t>(status), sitem_type, format);
+ static_cast<intptr_t>(status), sitem_type, format);
}
return status;
}
@@ -406,8 +394,7 @@
ASSERT(ret != NULL);
path.Printf("/%s", fname);
- char* result =
- reinterpret_cast<char*>(Dart_ScopeAllocate(path.length() + 1));
+ char* result = reinterpret_cast<char*>(Dart_ScopeAllocate(path.length() + 1));
return strncpy(result, path.buf(), path.length() + 1);
}
@@ -421,11 +408,10 @@
if (SSL_LOG_CERTS) {
Log::Print("Temporary keychain at: '%s'\n", temp_file_path);
}
- status = SecKeychainCreate(temp_file_path,
- strlen(temp_keychain_pwd) + 1,
+ status = SecKeychainCreate(temp_file_path, strlen(temp_keychain_pwd) + 1,
reinterpret_cast<const void*>(temp_keychain_pwd),
FALSE, // Prompt user? Definitely no.
- NULL, // Default access rights.
+ NULL, // Default access rights.
keychain);
if (status != noErr) {
return status;
@@ -454,7 +440,7 @@
CFArrayRef items = NULL;
if (SSL_LOG_CERTS) {
Log::Print("Trying PKCS12 import with: type = %d, format = %d\n",
- sitem_type, format);
+ sitem_type, format);
}
// The documentation for SecKeychainItemImport here:
@@ -490,12 +476,12 @@
*out_keychain = keychain;
}
- status = SecItemImport(
- cfdata, NULL, &format, &sitem_type, 0, ¶ms, keychain, &items);
+ status = SecItemImport(cfdata, NULL, &format, &sitem_type, 0, ¶ms,
+ keychain, &items);
if (status != noErr) {
if (SSL_LOG_CERTS) {
Log::Print("TrySecItemImport failed with: %ld, it = %d, format = %d\n",
- static_cast<intptr_t>(status), sitem_type, format);
+ static_cast<intptr_t>(status), sitem_type, format);
}
return status;
}
@@ -527,8 +513,8 @@
ASSERT(password != NULL);
OSStatus status = noErr;
- CFDataRef cfdata = CFDataCreateWithBytesNoCopy(
- NULL, buffer, length, kCFAllocatorNull);
+ CFDataRef cfdata =
+ CFDataCreateWithBytesNoCopy(NULL, buffer, length, kCFAllocatorNull);
CFStringRef cfpassword = CFStringCreateWithCStringNoCopy(
NULL, password, kCFStringEncodingUTF8, kCFAllocatorNull);
ASSERT(cfdata != NULL);
@@ -581,15 +567,11 @@
SSLCertContext* context = NULL;
if (!Dart_IsNull(context_object)) {
ThrowIfError(Dart_GetNativeInstanceField(
- context_object,
- kSecurityContextNativeFieldIndex,
+ context_object, kSecurityContextNativeFieldIndex,
reinterpret_cast<intptr_t*>(&context)));
}
- GetFilter(args)->Connect(dart_this,
- host_name,
- context,
- is_server,
+ GetFilter(args)->Connect(dart_this, host_name, context, is_server,
request_client_certificate,
require_client_certificate);
}
@@ -626,8 +608,7 @@
DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 2));
bool require_client_certificate =
DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 3));
- GetFilter(args)->Renegotiate(use_session_cache,
- request_client_certificate,
+ GetFilter(args)->Renegotiate(use_session_cache, request_client_certificate,
require_client_certificate);
}
@@ -646,8 +627,7 @@
void FUNCTION_NAME(SecureSocket_RegisterBadCertificateCallback)(
Dart_NativeArguments args) {
- Dart_Handle callback =
- ThrowIfError(Dart_GetNativeArgument(args, 1));
+ Dart_Handle callback = ThrowIfError(Dart_GetNativeArgument(args, 1));
if (!Dart_IsClosure(callback) && !Dart_IsNull(callback)) {
Dart_ThrowException(DartUtils::NewDartArgumentError(
"Illegal argument to RegisterBadCertificateCallback"));
@@ -656,8 +636,7 @@
}
-void FUNCTION_NAME(SecureSocket_PeerCertificate)
- (Dart_NativeArguments args) {
+void FUNCTION_NAME(SecureSocket_PeerCertificate)(Dart_NativeArguments args) {
Dart_SetReturnValue(args, GetFilter(args)->PeerCertificate());
}
@@ -693,8 +672,8 @@
SecKeychainRef keychain = NULL;
{
ScopedMemBuffer buffer(ThrowIfError(Dart_GetNativeArgument(args, 1)));
- status = ExtractSecItems(
- buffer.get(), buffer.length(), password, NULL, &key, &keychain);
+ status = ExtractSecItems(buffer.get(), buffer.length(), password, NULL,
+ &key, &keychain);
}
// Set the context fields. If there's a failure, release the items.
@@ -727,8 +706,8 @@
CFArrayRef certs = NULL;
{
ScopedMemBuffer buffer(ThrowIfError(Dart_GetNativeArgument(args, 1)));
- status = ExtractSecItems(
- buffer.get(), buffer.length(), password, &certs, NULL, NULL);
+ status = ExtractSecItems(buffer.get(), buffer.length(), password, &certs,
+ NULL, NULL);
}
// Set the field in the context. If there's a failure, release the certs,
@@ -765,8 +744,8 @@
CFArrayRef certs = NULL;
{
ScopedMemBuffer buffer(ThrowIfError(Dart_GetNativeArgument(args, 1)));
- status = ExtractSecItems(
- buffer.get(), buffer.length(), password, &certs, NULL, NULL);
+ status = ExtractSecItems(buffer.get(), buffer.length(), password, &certs,
+ NULL, NULL);
}
// Set the field in the context. If there's a failure, release the certs,
@@ -791,8 +770,8 @@
CFArrayRef certs = NULL;
{
ScopedMemBuffer buffer(ThrowIfError(Dart_GetNativeArgument(args, 1)));
- status = ExtractSecItems(
- buffer.get(), buffer.length(), password, &certs, NULL, NULL);
+ status = ExtractSecItems(buffer.get(), buffer.length(), password, &certs,
+ NULL, NULL);
}
// Set the field in the context. If there's a failure, release the certs,
@@ -820,7 +799,7 @@
CFStringRef name) {
char* issuer_name = NULL;
- CFTypeRef keys[] = { field };
+ CFTypeRef keys[] = {field};
CFArrayRef key_array = CFArrayCreate(NULL, keys, 1, &kCFTypeArrayCallBacks);
CFErrorRef error = NULL;
CFDictionaryRef cert_dict =
@@ -865,10 +844,9 @@
void FUNCTION_NAME(X509_Subject)(Dart_NativeArguments args) {
SecCertificateRef certificate = GetX509Certificate(args);
- char* subject_name = GetNameFromCert(
- certificate,
- kSecOIDX509V1SubjectName,
- reinterpret_cast<CFStringRef>(kSecOIDCommonName));
+ char* subject_name =
+ GetNameFromCert(certificate, kSecOIDX509V1SubjectName,
+ reinterpret_cast<CFStringRef>(kSecOIDCommonName));
if (subject_name == NULL) {
Dart_ThrowException(DartUtils::NewDartArgumentError(
"X509.subject failed to find subject's common name."));
@@ -880,10 +858,9 @@
void FUNCTION_NAME(X509_Issuer)(Dart_NativeArguments args) {
SecCertificateRef certificate = GetX509Certificate(args);
- char* issuer_name = GetNameFromCert(
- certificate,
- kSecOIDX509V1IssuerName,
- reinterpret_cast<CFStringRef>(kSecOIDCommonName));
+ char* issuer_name =
+ GetNameFromCert(certificate, kSecOIDX509V1IssuerName,
+ reinterpret_cast<CFStringRef>(kSecOIDCommonName));
if (issuer_name == NULL) {
Dart_ThrowException(DartUtils::NewDartArgumentError(
"X509.issuer failed to find issuer's common name."));
@@ -895,7 +872,7 @@
// Returns the number of seconds since the epoch from 'field'.
static int64_t GetTimeFromCert(SecCertificateRef certificate, CFTypeRef field) {
- CFTypeRef keys[] = { field };
+ CFTypeRef keys[] = {field};
CFArrayRef key_array = CFArrayCreate(NULL, keys, 1, &kCFTypeArrayCallBacks);
CFErrorRef error = NULL;
CFDictionaryRef cert_dict =
@@ -924,18 +901,20 @@
void FUNCTION_NAME(X509_StartValidity)(Dart_NativeArguments args) {
SecCertificateRef certificate = GetX509Certificate(args);
- int64_t seconds_since_epoch = GetTimeFromCert(certificate,
- kSecOIDX509V1ValidityNotBefore);
- Dart_SetReturnValue(args,
+ int64_t seconds_since_epoch =
+ GetTimeFromCert(certificate, kSecOIDX509V1ValidityNotBefore);
+ Dart_SetReturnValue(
+ args,
Dart_NewInteger(static_cast<int64_t>(seconds_since_epoch) * 1000LL));
}
void FUNCTION_NAME(X509_EndValidity)(Dart_NativeArguments args) {
SecCertificateRef certificate = GetX509Certificate(args);
- int64_t seconds_since_epoch = GetTimeFromCert(certificate,
- kSecOIDX509V1ValidityNotAfter);
- Dart_SetReturnValue(args,
+ int64_t seconds_since_epoch =
+ GetTimeFromCert(certificate, kSecOIDX509V1ValidityNotAfter);
+ Dart_SetReturnValue(
+ args,
Dart_NewInteger(static_cast<int64_t>(seconds_since_epoch) * 1000LL));
}
@@ -974,8 +953,8 @@
OSStatus status = filter->ProcessAllBuffers(starts, ends, in_handshake);
if (status == noErr) {
- CObjectArray* result = new CObjectArray(
- CObject::NewArray(SSLFilter::kNumBuffers * 2));
+ CObjectArray* result =
+ new CObjectArray(CObject::NewArray(SSLFilter::kNumBuffers * 2));
for (intptr_t i = 0; i < SSLFilter::kNumBuffers; ++i) {
result->SetAt(2 * i, new CObjectInt32(CObject::NewInt32(starts[i])));
result->SetAt(2 * i + 1, new CObjectInt32(CObject::NewInt32(ends[i])));
@@ -986,17 +965,17 @@
CFStringRef error_string = SecCopyErrorMessageString(status, NULL);
if (error_string == NULL) {
status_message.Printf("OSStatus = %ld: https://www.osstatus.com",
- static_cast<intptr_t>(status));
+ static_cast<intptr_t>(status));
} else {
char* error = CFStringRefToCString(error_string);
- status_message.Printf("OSStatus = %ld: %s",
- static_cast<intptr_t>(status), error);
+ status_message.Printf("OSStatus = %ld: %s", static_cast<intptr_t>(status),
+ error);
CFRelease(error_string);
}
CObjectArray* result = new CObjectArray(CObject::NewArray(2));
result->SetAt(0, new CObjectInt32(CObject::NewInt32(status)));
- result->SetAt(1, new CObjectString(CObject::NewString(
- status_message.buf())));
+ result->SetAt(1,
+ new CObjectString(CObject::NewString(status_message.buf())));
return result;
}
}
@@ -1042,8 +1021,8 @@
}
Dart_Handle buffer_handle =
ThrowIfError(Dart_HandleFromPersistent(dart_buffer_objects_[idx]));
- ThrowIfError(DartUtils::SetIntegerField(
- buffer_handle, "start", static_cast<int64_t>(value)));
+ ThrowIfError(DartUtils::SetIntegerField(buffer_handle, "start",
+ static_cast<int64_t>(value)));
}
@@ -1054,8 +1033,8 @@
}
Dart_Handle buffer_handle =
ThrowIfError(Dart_HandleFromPersistent(dart_buffer_objects_[idx]));
- ThrowIfError(DartUtils::SetIntegerField(
- buffer_handle, "end", static_cast<int64_t>(value)));
+ ThrowIfError(DartUtils::SetIntegerField(buffer_handle, "end",
+ static_cast<int64_t>(value)));
}
@@ -1189,8 +1168,8 @@
RETURN_IF_ERROR(secure_filter_impl_type);
Dart_Handle size_string = DartUtils::NewString("SIZE");
RETURN_IF_ERROR(size_string);
- Dart_Handle dart_buffer_size = Dart_GetField(
- secure_filter_impl_type, size_string);
+ Dart_Handle dart_buffer_size =
+ Dart_GetField(secure_filter_impl_type, size_string);
RETURN_IF_ERROR(dart_buffer_size);
int64_t buffer_size = 0;
@@ -1200,8 +1179,8 @@
Dart_Handle encrypted_size_string = DartUtils::NewString("ENCRYPTED_SIZE");
RETURN_IF_ERROR(encrypted_size_string);
- Dart_Handle dart_encrypted_buffer_size = Dart_GetField(
- secure_filter_impl_type, encrypted_size_string);
+ Dart_Handle dart_encrypted_buffer_size =
+ Dart_GetField(secure_filter_impl_type, encrypted_size_string);
RETURN_IF_ERROR(dart_encrypted_buffer_size);
int64_t encrypted_buffer_size = 0;
@@ -1309,34 +1288,25 @@
// Configure the context.
OSStatus status;
status = SSLSetPeerDomainName(ssl_context, hostname, strlen(hostname));
- CheckStatus(status,
- "TlsException",
- "Failed to set peer domain name");
+ CheckStatus(status, "TlsException", "Failed to set peer domain name");
- status = SSLSetIOFuncs(
- ssl_context, SSLFilter::SSLReadCallback, SSLFilter::SSLWriteCallback);
- CheckStatus(status,
- "TlsException",
- "Failed to set IO Callbacks");
+ status = SSLSetIOFuncs(ssl_context, SSLFilter::SSLReadCallback,
+ SSLFilter::SSLWriteCallback);
+ CheckStatus(status, "TlsException", "Failed to set IO Callbacks");
- status = SSLSetConnection(
- ssl_context, reinterpret_cast<SSLConnectionRef>(this));
- CheckStatus(status,
- "TlsException",
- "Failed to set connection object");
+ status =
+ SSLSetConnection(ssl_context, reinterpret_cast<SSLConnectionRef>(this));
+ CheckStatus(status, "TlsException", "Failed to set connection object");
// Always evaluate the certs manually so that we can cache the peer
// certificates in the context for calls to peerCertificate.
- status = SSLSetSessionOption(
- ssl_context, kSSLSessionOptionBreakOnServerAuth, true);
- CheckStatus(status,
- "TlsException",
- "Failed to set BreakOnServerAuth option");
+ status = SSLSetSessionOption(ssl_context, kSSLSessionOptionBreakOnServerAuth,
+ true);
+ CheckStatus(status, "TlsException", "Failed to set BreakOnServerAuth option");
status = SSLSetProtocolVersionMin(ssl_context, kTLSProtocol1);
- CheckStatus(status,
- "TlsException",
- "Failed to set minimum protocol version to kTLSProtocol1");
+ CheckStatus(status, "TlsException",
+ "Failed to set minimum protocol version to kTLSProtocol1");
// If the context has a private key and certificate chain, combine the
// private key and first certificate into a SecIdentityRef, and place that
@@ -1363,31 +1333,29 @@
}
if (context->cert_authorities() != NULL) {
- status = SSLSetCertificateAuthorities(
- ssl_context, context->cert_authorities(), true);
- CheckStatus(status,
- "TlsException",
- "Failed to set certificate authorities");
+ status = SSLSetCertificateAuthorities(ssl_context,
+ context->cert_authorities(), true);
+ CheckStatus(status, "TlsException",
+ "Failed to set certificate authorities");
}
if (is_server) {
SSLAuthenticate auth =
require_client_certificate
- ? kAlwaysAuthenticate
- : (request_client_certificate ? kTryAuthenticate : kNeverAuthenticate);
+ ? kAlwaysAuthenticate
+ : (request_client_certificate ? kTryAuthenticate
+ : kNeverAuthenticate);
status = SSLSetClientSideAuthenticate(ssl_context, auth);
- CheckStatus(status,
- "TlsException",
- "Failed to set client authentication mode");
+ CheckStatus(status, "TlsException",
+ "Failed to set client authentication mode");
// If we're at least trying client authentication, then break handshake
// for client authentication.
if (auth != kNeverAuthenticate) {
- status = SSLSetSessionOption(
- ssl_context, kSSLSessionOptionBreakOnClientAuth, true);
- CheckStatus(status,
- "TlsException",
- "Failed to set client authentication mode");
+ status = SSLSetSessionOption(ssl_context,
+ kSSLSessionOptionBreakOnClientAuth, true);
+ CheckStatus(status, "TlsException",
+ "Failed to set client authentication mode");
}
}
@@ -1404,9 +1372,9 @@
status = noErr;
in_handshake_ = true;
}
- CheckStatus(status,
- "HandshakeException",
- is_server_ ? "Handshake error in server" : "Handshake error in client");
+ CheckStatus(status, "HandshakeException", is_server_
+ ? "Handshake error in server"
+ : "Handshake error in client");
}
@@ -1425,7 +1393,7 @@
}
if (SSL_LOG_STATUS) {
Log::Print("Handshake error from SSLCopyPeerTrust(): %ld.\n",
- static_cast<intptr_t>(status));
+ static_cast<intptr_t>(status));
}
return status;
}
@@ -1433,7 +1401,7 @@
CFArrayRef trusted_certs = NULL;
if (cert_context_.get()->trusted_certs() != NULL) {
trusted_certs =
- CFArrayCreateCopy(NULL, cert_context_.get()->trusted_certs());
+ CFArrayCreateCopy(NULL, cert_context_.get()->trusted_certs());
} else {
trusted_certs = CFArrayCreate(NULL, NULL, 0, &kCFTypeArrayCallBacks);
}
@@ -1442,7 +1410,7 @@
if (status != noErr) {
if (SSL_LOG_STATUS) {
Log::Print("Handshake error from SecTrustSetAnchorCertificates: %ld\n",
- static_cast<intptr_t>(status));
+ static_cast<intptr_t>(status));
}
CFRelease(trusted_certs);
CFRelease(peer_trust);
@@ -1450,7 +1418,8 @@
}
if (SSL_LOG_STATUS) {
- Log::Print("Handshake %s built in root certs\n",
+ Log::Print(
+ "Handshake %s built in root certs\n",
cert_context_.get()->trust_builtin() ? "trusting" : "not trusting");
}
@@ -1662,7 +1631,8 @@
OSStatus SSLFilter::SSLReadCallback(SSLConnectionRef connection,
- void* data, size_t* data_requested) {
+ void* data,
+ size_t* data_requested) {
// Copy at most `data_requested` bytes from `buffers_[kReadEncrypted]` into
// `data`
ASSERT(connection != NULL);
@@ -1708,7 +1678,7 @@
if (SSL_LOG_DATA) {
Log::Print("SSLReadCallback: requested: %ld, read %ld bytes\n",
- *data_requested, data_read);
+ *data_requested, data_read);
}
filter->SetBufferStart(kReadEncrypted, start);
@@ -1727,11 +1697,10 @@
OSStatus status = noErr;
size_t bytes = 0;
if (length > 0) {
- status = SSLRead(
- ssl_context_,
- reinterpret_cast<void*>((buffers_[kReadPlaintext] + start)),
- length,
- &bytes);
+ status =
+ SSLRead(ssl_context_,
+ reinterpret_cast<void*>((buffers_[kReadPlaintext] + start)),
+ length, &bytes);
if (SSL_LOG_STATUS) {
Log::Print("SSLRead: status = %ld\n", static_cast<intptr_t>(status));
}
@@ -1742,7 +1711,7 @@
}
if (SSL_LOG_DATA) {
Log::Print("ProcessReadPlaintextBuffer: requested: %ld, read %ld bytes\n",
- length, bytes);
+ length, bytes);
}
*bytes_processed = static_cast<intptr_t>(bytes);
return status;
@@ -1750,7 +1719,8 @@
OSStatus SSLFilter::SSLWriteCallback(SSLConnectionRef connection,
- const void* data, size_t* data_provided) {
+ const void* data,
+ size_t* data_provided) {
// Copy at most `data_provided` bytes from data into
// `buffers_[kWriteEncrypted]`.
ASSERT(connection != NULL);
@@ -1758,7 +1728,7 @@
ASSERT(data_provided != NULL);
SSLFilter* filter =
- const_cast<SSLFilter*>(reinterpret_cast<const SSLFilter*>(connection));
+ const_cast<SSLFilter*>(reinterpret_cast<const SSLFilter*>(connection));
const uint8_t* datap = reinterpret_cast<const uint8_t*>(data);
uint8_t* buffer = filter->buffers_[kWriteEncrypted];
intptr_t start = filter->GetBufferStart(kWriteEncrypted);
@@ -1799,7 +1769,7 @@
if (SSL_LOG_DATA) {
Log::Print("SSLWriteCallback: provided: %ld, written %ld bytes\n",
- *data_provided, data_written);
+ *data_provided, data_written);
}
filter->SetBufferEnd(kWriteEncrypted, end);
@@ -1816,11 +1786,10 @@
OSStatus status = noErr;
size_t bytes = 0;
if (length > 0) {
- status = SSLWrite(
- ssl_context_,
- reinterpret_cast<void*>(buffers_[kWritePlaintext] + start),
- length,
- &bytes);
+ status =
+ SSLWrite(ssl_context_,
+ reinterpret_cast<void*>(buffers_[kWritePlaintext] + start),
+ length, &bytes);
if (SSL_LOG_STATUS) {
Log::Print("SSLWrite: status = %ld\n", static_cast<intptr_t>(status));
}
@@ -1831,7 +1800,7 @@
}
if (SSL_LOG_DATA) {
Log::Print("ProcessWritePlaintextBuffer: requested: %ld, written: %ld\n",
- length, bytes);
+ length, bytes);
}
*bytes_processed = static_cast<intptr_t>(bytes);
return status;
diff --git a/runtime/bin/secure_socket_macos.h b/runtime/bin/secure_socket_macos.h
index ae8f2e8..f84cc42 100644
--- a/runtime/bin/secure_socket_macos.h
+++ b/runtime/bin/secure_socket_macos.h
@@ -35,16 +35,15 @@
// thread. Setters return false if the field was already set.
class SSLCertContext : public ReferenceCounted<SSLCertContext> {
public:
- SSLCertContext() :
- ReferenceCounted(),
- mutex_(new Mutex()),
- private_key_(NULL),
- keychain_(NULL),
- cert_chain_(NULL),
- trusted_certs_(NULL),
- cert_authorities_(NULL),
- trust_builtin_(false) {
- }
+ SSLCertContext()
+ : ReferenceCounted(),
+ mutex_(new Mutex()),
+ private_key_(NULL),
+ keychain_(NULL),
+ cert_chain_(NULL),
+ trusted_certs_(NULL),
+ cert_authorities_(NULL),
+ trust_builtin_(false) {}
~SSLCertContext() {
{
@@ -191,8 +190,7 @@
connected_(false),
bad_cert_(false),
is_server_(false),
- hostname_(NULL) {
- }
+ hostname_(NULL) {}
~SSLFilter();
diff --git a/runtime/bin/secure_socket_unsupported.cc b/runtime/bin/secure_socket_unsupported.cc
index fb7e713..8ed4f24 100644
--- a/runtime/bin/secure_socket_unsupported.cc
+++ b/runtime/bin/secure_socket_unsupported.cc
@@ -71,15 +71,13 @@
}
-void FUNCTION_NAME(SecureSocket_InitializeLibrary)
- (Dart_NativeArguments args) {
+void FUNCTION_NAME(SecureSocket_InitializeLibrary)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewDartArgumentError(
"Secure Sockets unsupported on this platform"));
}
-void FUNCTION_NAME(SecureSocket_PeerCertificate)
- (Dart_NativeArguments args) {
+void FUNCTION_NAME(SecureSocket_PeerCertificate)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewDartArgumentError(
"Secure Sockets unsupported on this platform"));
}
diff --git a/runtime/bin/snapshot_in.cc b/runtime/bin/snapshot_in.cc
index 769d96c..1f63a86 100644
--- a/runtime/bin/snapshot_in.cc
+++ b/runtime/bin/snapshot_in.cc
@@ -2,6 +2,8 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
+// clang-format off
+
// This file is linked into the dart executable when it has a snapshot
// linked into it.
diff --git a/runtime/bin/socket.cc b/runtime/bin/socket.cc
index 687b773..17f5641 100644
--- a/runtime/bin/socket.cc
+++ b/runtime/bin/socket.cc
@@ -23,7 +23,7 @@
static const int kSocketIdNativeField = 0;
-ListeningSocketRegistry *globalTcpListeningSocketRegistry = NULL;
+ListeningSocketRegistry* globalTcpListeningSocketRegistry = NULL;
bool short_socket_read = false;
@@ -35,7 +35,7 @@
}
-ListeningSocketRegistry *ListeningSocketRegistry::Instance() {
+ListeningSocketRegistry* ListeningSocketRegistry::Instance() {
return globalTcpListeningSocketRegistry;
}
@@ -48,9 +48,8 @@
ListeningSocketRegistry::OSSocket* ListeningSocketRegistry::LookupByPort(
intptr_t port) {
- HashMap::Entry* entry =
- sockets_by_port_.Lookup(GetHashmapKeyFromIntptr(port),
- GetHashmapHashFromIntptr(port), false);
+ HashMap::Entry* entry = sockets_by_port_.Lookup(
+ GetHashmapKeyFromIntptr(port), GetHashmapHashFromIntptr(port), false);
if (entry == NULL) {
return NULL;
}
@@ -59,25 +58,23 @@
void ListeningSocketRegistry::InsertByPort(intptr_t port, OSSocket* socket) {
- HashMap::Entry* entry =
- sockets_by_port_.Lookup(GetHashmapKeyFromIntptr(port),
- GetHashmapHashFromIntptr(port), true);
+ HashMap::Entry* entry = sockets_by_port_.Lookup(
+ GetHashmapKeyFromIntptr(port), GetHashmapHashFromIntptr(port), true);
ASSERT(entry != NULL);
entry->value = reinterpret_cast<void*>(socket);
}
void ListeningSocketRegistry::RemoveByPort(intptr_t port) {
- sockets_by_port_.Remove(
- GetHashmapKeyFromIntptr(port), GetHashmapHashFromIntptr(port));
+ sockets_by_port_.Remove(GetHashmapKeyFromIntptr(port),
+ GetHashmapHashFromIntptr(port));
}
ListeningSocketRegistry::OSSocket* ListeningSocketRegistry::LookupByFd(
intptr_t fd) {
- HashMap::Entry* entry =
- sockets_by_fd_.Lookup(GetHashmapKeyFromIntptr(fd),
- GetHashmapHashFromIntptr(fd), false);
+ HashMap::Entry* entry = sockets_by_fd_.Lookup(
+ GetHashmapKeyFromIntptr(fd), GetHashmapHashFromIntptr(fd), false);
if (entry == NULL) {
return NULL;
}
@@ -86,17 +83,16 @@
void ListeningSocketRegistry::InsertByFd(intptr_t fd, OSSocket* socket) {
- HashMap::Entry* entry =
- sockets_by_fd_.Lookup(GetHashmapKeyFromIntptr(fd),
- GetHashmapHashFromIntptr(fd), true);
+ HashMap::Entry* entry = sockets_by_fd_.Lookup(
+ GetHashmapKeyFromIntptr(fd), GetHashmapHashFromIntptr(fd), true);
ASSERT(entry != NULL);
entry->value = reinterpret_cast<void*>(socket);
}
void ListeningSocketRegistry::RemoveByFd(intptr_t fd) {
- sockets_by_fd_.Remove(
- GetHashmapKeyFromIntptr(fd), GetHashmapHashFromIntptr(fd));
+ sockets_by_fd_.Remove(GetHashmapKeyFromIntptr(fd),
+ GetHashmapHashFromIntptr(fd));
}
@@ -113,8 +109,8 @@
// There is already a socket listening on this port. We need to ensure
// that if there is one also listening on the same address, it was created
// with `shared = true`, ...
- OSSocket *os_socket = first_os_socket;
- OSSocket *os_socket_same_addr = findOSSocketWithAddress(os_socket, addr);
+ OSSocket* os_socket = first_os_socket;
+ OSSocket* os_socket_same_addr = findOSSocketWithAddress(os_socket, addr);
if (os_socket_same_addr != NULL) {
if (!os_socket_same_addr->shared || !shared) {
@@ -122,7 +118,7 @@
"The shared flag to bind() needs to be `true` if "
"binding multiple times on the same (address, port) "
"combination.",
- OSError::kUnknown);
+ OSError::kUnknown);
return DartUtils::NewDartOSError(&os_error);
}
if (os_socket_same_addr->v6_only != v6_only) {
@@ -130,7 +126,7 @@
"The v6Only flag to bind() needs to be the same if "
"binding multiple times on the same (address, port) "
"combination.",
- OSError::kUnknown);
+ OSError::kUnknown);
return DartUtils::NewDartOSError(&os_error);
}
@@ -163,7 +159,7 @@
intptr_t allocated_port = Socket::GetPort(socketfd);
ASSERT(allocated_port > 0);
- OSSocket *os_socket =
+ OSSocket* os_socket =
new OSSocket(addr, allocated_port, v6_only, shared, socketfd);
os_socket->ref_count = 1;
os_socket->next = first_os_socket;
@@ -216,8 +212,7 @@
void ListeningSocketRegistry::CloseAllSafe() {
MutexLocker ml(mutex_);
- for (HashMap::Entry* p = sockets_by_fd_.Start();
- p != NULL;
+ for (HashMap::Entry* p = sockets_by_fd_.Start(); p != NULL;
p = sockets_by_fd_.Next(p)) {
CloseOneSafe(reinterpret_cast<OSSocket*>(p->value));
}
@@ -440,16 +435,12 @@
Dart_PropagateError(dart_args[3]);
}
// TODO(sgjesse): Cache the _makeDatagram function somewhere.
- Dart_Handle io_lib =
- Dart_LookupLibrary(DartUtils::NewString("dart:io"));
+ Dart_Handle io_lib = Dart_LookupLibrary(DartUtils::NewString("dart:io"));
if (Dart_IsError(io_lib)) {
Dart_PropagateError(io_lib);
}
- Dart_Handle result =
- Dart_Invoke(io_lib,
- DartUtils::NewString("_makeDatagram"),
- kNumArgs,
- dart_args);
+ Dart_Handle result = Dart_Invoke(
+ io_lib, DartUtils::NewString("_makeDatagram"), kNumArgs, dart_args);
Dart_SetReturnValue(args, result);
}
@@ -459,10 +450,8 @@
Socket::GetSocketIdNativeField(Dart_GetNativeArgument(args, 0));
Dart_Handle buffer_obj = Dart_GetNativeArgument(args, 1);
ASSERT(Dart_IsList(buffer_obj));
- intptr_t offset =
- DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 2));
- intptr_t length =
- DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 3));
+ intptr_t offset = DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 2));
+ intptr_t length = DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 3));
bool short_write = false;
if (short_socket_write) {
if (length > 1) {
@@ -503,18 +492,14 @@
intptr_t socket =
Socket::GetSocketIdNativeField(Dart_GetNativeArgument(args, 0));
Dart_Handle buffer_obj = Dart_GetNativeArgument(args, 1);
- intptr_t offset =
- DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 2));
- intptr_t length =
- DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 3));
+ intptr_t offset = DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 2));
+ intptr_t length = DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 3));
Dart_Handle address_obj = Dart_GetNativeArgument(args, 4);
ASSERT(Dart_IsList(address_obj));
RawAddr addr;
SocketAddress::GetSockAddr(address_obj, &addr);
int64_t port = DartUtils::GetInt64ValueCheckRange(
- Dart_GetNativeArgument(args, 5),
- 0,
- 65535);
+ Dart_GetNativeArgument(args, 5), 0, 65535);
SocketAddress::SetAddrPort(&addr, port);
Dart_TypedData_Type type;
uint8_t* buffer = NULL;
@@ -604,8 +589,8 @@
void FUNCTION_NAME(Socket_GetStdioHandle)(Dart_NativeArguments args) {
- int64_t num = DartUtils::GetInt64ValueCheckRange(
- Dart_GetNativeArgument(args, 1), 0, 2);
+ int64_t num =
+ DartUtils::GetInt64ValueCheckRange(Dart_GetNativeArgument(args, 1), 0, 2);
intptr_t socket = Socket::GetStdioHandle(num);
Socket::SetSocketIdNativeField(Dart_GetNativeArgument(args, 0), socket);
Dart_SetReturnValue(args, Dart_NewBoolean(socket >= 0));
@@ -628,14 +613,10 @@
RawAddr addr;
SocketAddress::GetSockAddr(Dart_GetNativeArgument(args, 1), &addr);
int64_t port = DartUtils::GetInt64ValueCheckRange(
- Dart_GetNativeArgument(args, 2),
- 0,
- 65535);
+ Dart_GetNativeArgument(args, 2), 0, 65535);
SocketAddress::SetAddrPort(&addr, port);
int64_t backlog = DartUtils::GetInt64ValueCheckRange(
- Dart_GetNativeArgument(args, 3),
- 0,
- 65535);
+ Dart_GetNativeArgument(args, 3), 0, 65535);
bool v6_only = DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 4));
bool shared = DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 5));
@@ -662,8 +643,7 @@
CObject* Socket::LookupRequest(const CObjectArray& request) {
- if ((request.Length() == 2) &&
- request[0]->IsString() &&
+ if ((request.Length() == 2) && request[0]->IsString() &&
request[1]->IsInt32()) {
CObjectString host(request[0]);
CObjectInt32 type(request[1]);
@@ -672,19 +652,19 @@
AddressList<SocketAddress>* addresses =
Socket::LookupAddress(host.CString(), type.Value(), &os_error);
if (addresses != NULL) {
- CObjectArray* array = new CObjectArray(
- CObject::NewArray(addresses->count() + 1));
+ CObjectArray* array =
+ new CObjectArray(CObject::NewArray(addresses->count() + 1));
array->SetAt(0, new CObjectInt32(CObject::NewInt32(0)));
for (intptr_t i = 0; i < addresses->count(); i++) {
SocketAddress* addr = addresses->GetAt(i);
CObjectArray* entry = new CObjectArray(CObject::NewArray(3));
- CObjectInt32* type = new CObjectInt32(
- CObject::NewInt32(addr->GetType()));
+ CObjectInt32* type =
+ new CObjectInt32(CObject::NewInt32(addr->GetType()));
entry->SetAt(0, type);
- CObjectString* as_string = new CObjectString(CObject::NewString(
- addr->as_string()));
+ CObjectString* as_string =
+ new CObjectString(CObject::NewString(addr->as_string()));
entry->SetAt(1, as_string);
RawAddr raw = addr->addr();
@@ -706,23 +686,20 @@
CObject* Socket::ReverseLookupRequest(const CObjectArray& request) {
- if ((request.Length() == 1) &&
- request[0]->IsTypedData()) {
+ if ((request.Length() == 1) && request[0]->IsTypedData()) {
CObjectUint8Array addr_object(request[0]);
RawAddr addr;
int len = addr_object.Length();
memset(reinterpret_cast<void*>(&addr), 0, sizeof(RawAddr));
if (len == sizeof(in_addr)) {
addr.in.sin_family = AF_INET;
- memmove(reinterpret_cast<void*>(&addr.in.sin_addr),
- addr_object.Buffer(),
+ memmove(reinterpret_cast<void*>(&addr.in.sin_addr), addr_object.Buffer(),
len);
} else {
ASSERT(len == sizeof(in6_addr));
addr.in6.sin6_family = AF_INET6;
memmove(reinterpret_cast<void*>(&addr.in6.sin6_addr),
- addr_object.Buffer(),
- len);
+ addr_object.Buffer(), len);
}
OSError* os_error = NULL;
@@ -741,40 +718,39 @@
CObject* Socket::ListInterfacesRequest(const CObjectArray& request) {
- if ((request.Length() == 1) &&
- request[0]->IsInt32()) {
+ if ((request.Length() == 1) && request[0]->IsInt32()) {
CObjectInt32 type(request[0]);
CObject* result = NULL;
OSError* os_error = NULL;
- AddressList<InterfaceSocketAddress>* addresses = Socket::ListInterfaces(
- type.Value(), &os_error);
+ AddressList<InterfaceSocketAddress>* addresses =
+ Socket::ListInterfaces(type.Value(), &os_error);
if (addresses != NULL) {
- CObjectArray* array = new CObjectArray(
- CObject::NewArray(addresses->count() + 1));
+ CObjectArray* array =
+ new CObjectArray(CObject::NewArray(addresses->count() + 1));
array->SetAt(0, new CObjectInt32(CObject::NewInt32(0)));
for (intptr_t i = 0; i < addresses->count(); i++) {
InterfaceSocketAddress* interface = addresses->GetAt(i);
SocketAddress* addr = interface->socket_address();
CObjectArray* entry = new CObjectArray(CObject::NewArray(5));
- CObjectInt32* type = new CObjectInt32(
- CObject::NewInt32(addr->GetType()));
+ CObjectInt32* type =
+ new CObjectInt32(CObject::NewInt32(addr->GetType()));
entry->SetAt(0, type);
- CObjectString* as_string = new CObjectString(CObject::NewString(
- addr->as_string()));
+ CObjectString* as_string =
+ new CObjectString(CObject::NewString(addr->as_string()));
entry->SetAt(1, as_string);
RawAddr raw = addr->addr();
CObjectUint8Array* data = SocketAddress::ToCObject(raw);
entry->SetAt(2, data);
- CObjectString* interface_name = new CObjectString(CObject::NewString(
- interface->interface_name()));
+ CObjectString* interface_name =
+ new CObjectString(CObject::NewString(interface->interface_name()));
entry->SetAt(3, interface_name);
- CObjectInt64* interface_index = new CObjectInt64(CObject::NewInt64(
- interface->interface_index()));
+ CObjectInt64* interface_index =
+ new CObjectInt64(CObject::NewInt64(interface->interface_index()));
entry->SetAt(4, interface_index);
array->SetAt(i + 1, entry);
@@ -795,9 +771,8 @@
intptr_t socket =
Socket::GetSocketIdNativeField(Dart_GetNativeArgument(args, 0));
int64_t option = DartUtils::GetIntegerValue(Dart_GetNativeArgument(args, 1));
- intptr_t protocol =
- static_cast<intptr_t>(
- DartUtils::GetIntegerValue(Dart_GetNativeArgument(args, 2)));
+ intptr_t protocol = static_cast<intptr_t>(
+ DartUtils::GetIntegerValue(Dart_GetNativeArgument(args, 2)));
bool ok = false;
switch (option) {
case 0: { // TCP_NODELAY.
@@ -853,8 +828,7 @@
Socket::GetSocketIdNativeField(Dart_GetNativeArgument(args, 0));
int64_t option = DartUtils::GetIntegerValue(Dart_GetNativeArgument(args, 1));
int64_t protocol = DartUtils::GetInt64ValueCheckRange(
- Dart_GetNativeArgument(args, 2),
- SocketAddress::TYPE_IPV4,
+ Dart_GetNativeArgument(args, 2), SocketAddress::TYPE_IPV4,
SocketAddress::TYPE_IPV6);
switch (option) {
case 0: // TCP_NODELAY.
@@ -863,14 +837,12 @@
break;
case 1: // IP_MULTICAST_LOOP.
result = Socket::SetMulticastLoop(
- socket,
- protocol,
+ socket, protocol,
DartUtils::GetBooleanValue(Dart_GetNativeArgument(args, 3)));
break;
case 2: // IP_MULTICAST_TTL.
result = Socket::SetMulticastHops(
- socket,
- protocol,
+ socket, protocol,
DartUtils::GetIntegerValue(Dart_GetNativeArgument(args, 3)));
break;
case 3: { // IP_MULTICAST_IF.
diff --git a/runtime/bin/socket.h b/runtime/bin/socket.h
index 7b3985e..35d4acc 100644
--- a/runtime/bin/socket.h
+++ b/runtime/bin/socket.h
@@ -74,14 +74,14 @@
static intptr_t GetAddrLength(const RawAddr& addr) {
ASSERT((addr.ss.ss_family == AF_INET) || (addr.ss.ss_family == AF_INET6));
- return (addr.ss.ss_family == AF_INET6) ?
- sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
+ return (addr.ss.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6)
+ : sizeof(struct sockaddr_in);
}
static intptr_t GetInAddrLength(const RawAddr& addr) {
ASSERT((addr.ss.ss_family == AF_INET) || (addr.ss.ss_family == AF_INET6));
- return (addr.ss.ss_family == AF_INET6) ?
- sizeof(struct in6_addr) : sizeof(struct in_addr);
+ return (addr.ss.ss_family == AF_INET6) ? sizeof(struct in6_addr)
+ : sizeof(struct in_addr);
}
static bool AreAddressesEqual(const RawAddr& a, const RawAddr& b) {
@@ -94,8 +94,7 @@
if (b.ss.ss_family != AF_INET6) {
return false;
}
- return memcmp(&a.in6.sin6_addr,
- &b.in6.sin6_addr,
+ return memcmp(&a.in6.sin6_addr, &b.in6.sin6_addr,
sizeof(a.in6.sin6_addr)) == 0;
} else {
UNREACHABLE();
@@ -120,7 +119,7 @@
memset(reinterpret_cast<void*>(addr), 0, sizeof(RawAddr));
if (len == sizeof(in_addr)) {
addr->in.sin_family = AF_INET;
- memmove(reinterpret_cast<void *>(&addr->in.sin_addr), data, len);
+ memmove(reinterpret_cast<void*>(&addr->in.sin_addr), data, len);
} else {
ASSERT(len == sizeof(in6_addr));
addr->in6.sin6_family = AF_INET6;
@@ -165,8 +164,8 @@
Dart_Handle err;
if (addr.addr.sa_family == AF_INET6) {
err = Dart_ListSetAsBytes(
- result, 0,
- reinterpret_cast<const uint8_t*>(&addr.in6.sin6_addr), len);
+ result, 0, reinterpret_cast<const uint8_t*>(&addr.in6.sin6_addr),
+ len);
} else {
err = Dart_ListSetAsBytes(
result, 0, reinterpret_cast<const uint8_t*>(&addr.in.sin_addr), len);
@@ -208,9 +207,7 @@
interface_name_(interface_name),
interface_index_(interface_index) {}
- ~InterfaceSocketAddress() {
- delete socket_address_;
- }
+ ~InterfaceSocketAddress() { delete socket_address_; }
SocketAddress* socket_address() const { return socket_address_; }
const char* interface_name() const { return interface_name_; }
@@ -225,12 +222,11 @@
};
-template<typename T>
+template <typename T>
class AddressList {
public:
explicit AddressList(intptr_t count)
- : count_(count),
- addresses_(new T*[count_]) {}
+ : count_(count), addresses_(new T*[count_]) {}
~AddressList() {
for (intptr_t i = 0; i < count_; i++) {
@@ -266,10 +262,14 @@
// Send data on a socket. The port to send to is specified in the port
// component of the passed RawAddr structure. The RawAddr structure is only
// used for datagram sockets.
- static intptr_t SendTo(
- intptr_t fd, const void* buffer, intptr_t num_bytes, const RawAddr& addr);
- static intptr_t RecvFrom(
- intptr_t fd, void* buffer, intptr_t num_bytes, RawAddr* addr);
+ static intptr_t SendTo(intptr_t fd,
+ const void* buffer,
+ intptr_t num_bytes,
+ const RawAddr& addr);
+ static intptr_t RecvFrom(intptr_t fd,
+ void* buffer,
+ intptr_t num_bytes,
+ RawAddr* addr);
// Creates a socket which is bound and connected. The port to connect to is
// specified as the port component of the passed RawAddr structure.
static intptr_t CreateConnect(const RawAddr& addr);
@@ -372,10 +372,10 @@
class ListeningSocketRegistry {
public:
- ListeningSocketRegistry() :
- sockets_by_port_(SameIntptrValue, kInitialSocketsCount),
- sockets_by_fd_(SameIntptrValue, kInitialSocketsCount),
- mutex_(new Mutex()) {}
+ ListeningSocketRegistry()
+ : sockets_by_port_(SameIntptrValue, kInitialSocketsCount),
+ sockets_by_fd_(SameIntptrValue, kInitialSocketsCount),
+ mutex_(new Mutex()) {}
~ListeningSocketRegistry() {
CloseAllSafe();
@@ -385,7 +385,7 @@
static void Initialize();
- static ListeningSocketRegistry *Instance();
+ static ListeningSocketRegistry* Instance();
static void Cleanup();
@@ -407,7 +407,7 @@
// this function.
bool CloseSafe(intptr_t socketfd);
- Mutex *mutex() { return mutex_; }
+ Mutex* mutex() { return mutex_; }
private:
struct OSSocket {
@@ -420,17 +420,25 @@
// Singly linked lists of OSSocket instances which listen on the same port
// but on different addresses.
- OSSocket *next;
+ OSSocket* next;
- OSSocket(RawAddr address, int port, bool v6_only, bool shared,
+ OSSocket(RawAddr address,
+ int port,
+ bool v6_only,
+ bool shared,
intptr_t socketfd)
- : address(address), port(port), v6_only(v6_only), shared(shared),
- ref_count(0), socketfd(socketfd), next(NULL) {}
+ : address(address),
+ port(port),
+ v6_only(v6_only),
+ shared(shared),
+ ref_count(0),
+ socketfd(socketfd),
+ next(NULL) {}
};
static const intptr_t kInitialSocketsCount = 8;
- OSSocket *findOSSocketWithAddress(OSSocket *current, const RawAddr& addr) {
+ OSSocket* findOSSocketWithAddress(OSSocket* current, const RawAddr& addr) {
while (current != NULL) {
if (SocketAddress::AreAddressesEqual(current->address, addr)) {
return current;
@@ -467,7 +475,7 @@
HashMap sockets_by_port_;
HashMap sockets_by_fd_;
- Mutex *mutex_;
+ Mutex* mutex_;
DISALLOW_COPY_AND_ASSIGN(ListeningSocketRegistry);
};
diff --git a/runtime/bin/socket_android.cc b/runtime/bin/socket_android.cc
index caddb3a..ae83b47 100644
--- a/runtime/bin/socket_android.cc
+++ b/runtime/bin/socket_android.cc
@@ -10,13 +10,13 @@
#include "bin/socket.h"
#include "bin/socket_android.h"
-#include <errno.h> // NOLINT
+#include <errno.h> // NOLINT
#include <netinet/tcp.h> // NOLINT
-#include <stdio.h> // NOLINT
-#include <stdlib.h> // NOLINT
-#include <string.h> // NOLINT
-#include <sys/stat.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <stdio.h> // NOLINT
+#include <stdlib.h> // NOLINT
+#include <string.h> // NOLINT
+#include <sys/stat.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/fdutils.h"
#include "bin/file.h"
@@ -27,19 +27,19 @@
SocketAddress::SocketAddress(struct sockaddr* sa) {
ASSERT(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN);
- if (!Socket::FormatNumericAddress(
- *reinterpret_cast<RawAddr*>(sa), as_string_, INET6_ADDRSTRLEN)) {
+ if (!Socket::FormatNumericAddress(*reinterpret_cast<RawAddr*>(sa), as_string_,
+ INET6_ADDRSTRLEN)) {
as_string_[0] = 0;
}
socklen_t salen = GetAddrLength(*reinterpret_cast<RawAddr*>(sa));
- memmove(reinterpret_cast<void *>(&addr_), sa, salen);
+ memmove(reinterpret_cast<void*>(&addr_), sa, salen);
}
bool Socket::FormatNumericAddress(const RawAddr& addr, char* address, int len) {
socklen_t salen = SocketAddress::GetAddrLength(addr);
- return (NO_RETRY_EXPECTED(getnameinfo(
- &addr.addr, salen, address, len, NULL, 0, NI_NUMERICHOST)) == 0);
+ return (NO_RETRY_EXPECTED(getnameinfo(&addr.addr, salen, address, len, NULL,
+ 0, NI_NUMERICHOST)) == 0);
}
@@ -103,7 +103,7 @@
bool Socket::IsBindError(intptr_t error_number) {
return error_number == EADDRINUSE || error_number == EADDRNOTAVAIL ||
- error_number == EINVAL;
+ error_number == EINVAL;
}
@@ -125,8 +125,10 @@
}
-intptr_t Socket::RecvFrom(
- intptr_t fd, void* buffer, intptr_t num_bytes, RawAddr* addr) {
+intptr_t Socket::RecvFrom(intptr_t fd,
+ void* buffer,
+ intptr_t num_bytes,
+ RawAddr* addr) {
ASSERT(fd >= 0);
socklen_t addr_len = sizeof(addr->ss);
ssize_t read_bytes = TEMP_FAILURE_RETRY(
@@ -153,12 +155,14 @@
}
-intptr_t Socket::SendTo(
- intptr_t fd, const void* buffer, intptr_t num_bytes, const RawAddr& addr) {
+intptr_t Socket::SendTo(intptr_t fd,
+ const void* buffer,
+ intptr_t num_bytes,
+ const RawAddr& addr) {
ASSERT(fd >= 0);
- ssize_t written_bytes = TEMP_FAILURE_RETRY(
- sendto(fd, buffer, num_bytes, 0,
- &addr.addr, SocketAddress::GetAddrLength(addr)));
+ ssize_t written_bytes =
+ TEMP_FAILURE_RETRY(sendto(fd, buffer, num_bytes, 0, &addr.addr,
+ SocketAddress::GetAddrLength(addr)));
ASSERT(EAGAIN == EWOULDBLOCK);
if ((written_bytes == -1) && (errno == EWOULDBLOCK)) {
// If the would block we need to retry and therefore return 0 as
@@ -195,10 +199,7 @@
void Socket::GetError(intptr_t fd, OSError* os_error) {
int errorNumber;
socklen_t len = sizeof(errorNumber);
- getsockopt(fd,
- SOL_SOCKET,
- SO_ERROR,
- reinterpret_cast<void*>(&errorNumber),
+ getsockopt(fd, SOL_SOCKET, SO_ERROR, reinterpret_cast<void*>(&errorNumber),
&len);
os_error->SetCodeAndMessage(OSError::kSystem, errorNumber);
}
@@ -247,9 +248,8 @@
status = getaddrinfo(host, 0, &hints, &info);
if (status != 0) {
ASSERT(*os_error == NULL);
- *os_error = new OSError(status,
- gai_strerror(status),
- OSError::kGetAddressInfo);
+ *os_error =
+ new OSError(status, gai_strerror(status), OSError::kGetAddressInfo);
return NULL;
}
}
@@ -277,19 +277,13 @@
intptr_t host_len,
OSError** os_error) {
ASSERT(host_len >= NI_MAXHOST);
- int status = NO_RETRY_EXPECTED(getnameinfo(
- &addr.addr,
- SocketAddress::GetAddrLength(addr),
- host,
- host_len,
- NULL,
- 0,
- NI_NAMEREQD));
+ int status = NO_RETRY_EXPECTED(
+ getnameinfo(&addr.addr, SocketAddress::GetAddrLength(addr), host,
+ host_len, NULL, 0, NI_NAMEREQD));
if (status != 0) {
ASSERT(*os_error == NULL);
- *os_error = new OSError(status,
- gai_strerror(status),
- OSError::kGetAddressInfo);
+ *os_error =
+ new OSError(status, gai_strerror(status), OSError::kGetAddressInfo);
return false;
}
return true;
@@ -325,9 +319,7 @@
}
if (NO_RETRY_EXPECTED(
- bind(fd,
- &addr.addr,
- SocketAddress::GetAddrLength(addr))) < 0) {
+ bind(fd, &addr.addr, SocketAddress::GetAddrLength(addr))) < 0) {
VOID_TEMP_FAILURE_RETRY(close(fd));
return -1;
}
@@ -379,9 +371,7 @@
}
if (NO_RETRY_EXPECTED(
- bind(fd,
- &addr.addr,
- SocketAddress::GetAddrLength(addr))) < 0) {
+ bind(fd, &addr.addr, SocketAddress::GetAddrLength(addr))) < 0) {
VOID_TEMP_FAILURE_RETRY(close(fd));
return -1;
}
@@ -418,9 +408,9 @@
// On Android a number of protocol errors should be treated as EAGAIN.
// These are the ones for TCP/IP.
return (error == EAGAIN) || (error == ENETDOWN) || (error == EPROTO) ||
- (error == ENOPROTOOPT) || (error == EHOSTDOWN) || (error == ENONET) ||
- (error == EHOSTUNREACH) || (error == EOPNOTSUPP) ||
- (error == ENETUNREACH);
+ (error == ENOPROTOOPT) || (error == EHOSTDOWN) || (error == ENONET) ||
+ (error == EHOSTUNREACH) || (error == EOPNOTSUPP) ||
+ (error == ENETUNREACH);
}
@@ -454,11 +444,8 @@
bool Socket::GetNoDelay(intptr_t fd, bool* enabled) {
int on;
socklen_t len = sizeof(on);
- int err = NO_RETRY_EXPECTED(getsockopt(fd,
- IPPROTO_TCP,
- TCP_NODELAY,
- reinterpret_cast<void *>(&on),
- &len));
+ int err = NO_RETRY_EXPECTED(getsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
+ reinterpret_cast<void*>(&on), &len));
if (err == 0) {
*enabled = (on == 1);
}
@@ -468,10 +455,8 @@
bool Socket::SetNoDelay(intptr_t fd, bool enabled) {
int on = enabled ? 1 : 0;
- return NO_RETRY_EXPECTED(setsockopt(fd,
- IPPROTO_TCP,
- TCP_NODELAY,
- reinterpret_cast<char *>(&on),
+ return NO_RETRY_EXPECTED(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
+ reinterpret_cast<char*>(&on),
sizeof(on))) == 0;
}
@@ -480,13 +465,10 @@
uint8_t on;
socklen_t len = sizeof(on);
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_LOOP : IPV6_MULTICAST_LOOP;
- if (NO_RETRY_EXPECTED(getsockopt(fd,
- level,
- optname,
- reinterpret_cast<char *>(&on),
- &len)) == 0) {
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_LOOP
+ : IPV6_MULTICAST_LOOP;
+ if (NO_RETRY_EXPECTED(getsockopt(fd, level, optname,
+ reinterpret_cast<char*>(&on), &len)) == 0) {
*enabled = (on == 1);
return true;
}
@@ -497,26 +479,21 @@
bool Socket::SetMulticastLoop(intptr_t fd, intptr_t protocol, bool enabled) {
int on = enabled ? 1 : 0;
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_LOOP : IPV6_MULTICAST_LOOP;
- return NO_RETRY_EXPECTED(setsockopt(fd,
- level,
- optname,
- reinterpret_cast<char *>(&on),
- sizeof(on))) == 0;
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_LOOP
+ : IPV6_MULTICAST_LOOP;
+ return NO_RETRY_EXPECTED(setsockopt(
+ fd, level, optname, reinterpret_cast<char*>(&on), sizeof(on))) ==
+ 0;
}
bool Socket::GetMulticastHops(intptr_t fd, intptr_t protocol, int* value) {
uint8_t v;
socklen_t len = sizeof(v);
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_TTL : IPV6_MULTICAST_HOPS;
- if (NO_RETRY_EXPECTED(getsockopt(fd,
- level,
- optname,
- reinterpret_cast<char *>(&v),
- &len)) == 0) {
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_TTL
+ : IPV6_MULTICAST_HOPS;
+ if (NO_RETRY_EXPECTED(getsockopt(fd, level, optname,
+ reinterpret_cast<char*>(&v), &len)) == 0) {
*value = v;
return true;
}
@@ -527,24 +504,18 @@
bool Socket::SetMulticastHops(intptr_t fd, intptr_t protocol, int value) {
int v = value;
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_TTL : IPV6_MULTICAST_HOPS;
- return NO_RETRY_EXPECTED(setsockopt(fd,
- level,
- optname,
- reinterpret_cast<char *>(&v),
- sizeof(v))) == 0;
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_TTL
+ : IPV6_MULTICAST_HOPS;
+ return NO_RETRY_EXPECTED(setsockopt(
+ fd, level, optname, reinterpret_cast<char*>(&v), sizeof(v))) == 0;
}
bool Socket::GetBroadcast(intptr_t fd, bool* enabled) {
int on;
socklen_t len = sizeof(on);
- int err = NO_RETRY_EXPECTED(getsockopt(fd,
- SOL_SOCKET,
- SO_BROADCAST,
- reinterpret_cast<char *>(&on),
- &len));
+ int err = NO_RETRY_EXPECTED(getsockopt(fd, SOL_SOCKET, SO_BROADCAST,
+ reinterpret_cast<char*>(&on), &len));
if (err == 0) {
*enabled = (on == 1);
}
@@ -554,33 +525,35 @@
bool Socket::SetBroadcast(intptr_t fd, bool enabled) {
int on = enabled ? 1 : 0;
- return NO_RETRY_EXPECTED(setsockopt(fd,
- SOL_SOCKET,
- SO_BROADCAST,
- reinterpret_cast<char *>(&on),
+ return NO_RETRY_EXPECTED(setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
+ reinterpret_cast<char*>(&on),
sizeof(on))) == 0;
}
-bool Socket::JoinMulticast(
- intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
+bool Socket::JoinMulticast(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr&,
+ int interfaceIndex) {
int proto = (addr.addr.sa_family == AF_INET) ? IPPROTO_IP : IPPROTO_IPV6;
struct group_req mreq;
mreq.gr_interface = interfaceIndex;
memmove(&mreq.gr_group, &addr.ss, SocketAddress::GetAddrLength(addr));
- return NO_RETRY_EXPECTED(setsockopt(
- fd, proto, MCAST_JOIN_GROUP, &mreq, sizeof(mreq))) == 0;
+ return NO_RETRY_EXPECTED(
+ setsockopt(fd, proto, MCAST_JOIN_GROUP, &mreq, sizeof(mreq))) == 0;
}
-bool Socket::LeaveMulticast(
- intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
+bool Socket::LeaveMulticast(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr&,
+ int interfaceIndex) {
int proto = (addr.addr.sa_family == AF_INET) ? IPPROTO_IP : IPPROTO_IPV6;
struct group_req mreq;
mreq.gr_interface = interfaceIndex;
memmove(&mreq.gr_group, &addr.ss, SocketAddress::GetAddrLength(addr));
- return NO_RETRY_EXPECTED(setsockopt(
- fd, proto, MCAST_LEAVE_GROUP, &mreq, sizeof(mreq))) == 0;
+ return NO_RETRY_EXPECTED(setsockopt(fd, proto, MCAST_LEAVE_GROUP, &mreq,
+ sizeof(mreq))) == 0;
}
} // namespace bin
diff --git a/runtime/bin/socket_fuchsia.cc b/runtime/bin/socket_fuchsia.cc
index b3935eb..7e8489b 100644
--- a/runtime/bin/socket_fuchsia.cc
+++ b/runtime/bin/socket_fuchsia.cc
@@ -63,8 +63,10 @@
}
-intptr_t Socket::RecvFrom(
- intptr_t fd, void* buffer, intptr_t num_bytes, RawAddr* addr) {
+intptr_t Socket::RecvFrom(intptr_t fd,
+ void* buffer,
+ intptr_t num_bytes,
+ RawAddr* addr) {
UNIMPLEMENTED();
return -1;
}
@@ -76,8 +78,10 @@
}
-intptr_t Socket::SendTo(
- intptr_t fd, const void* buffer, intptr_t num_bytes, const RawAddr& addr) {
+intptr_t Socket::SendTo(intptr_t fd,
+ const void* buffer,
+ intptr_t num_bytes,
+ const RawAddr& addr) {
UNIMPLEMENTED();
return -1;
}
@@ -232,15 +236,19 @@
}
-bool Socket::JoinMulticast(
- intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
+bool Socket::JoinMulticast(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr&,
+ int interfaceIndex) {
UNIMPLEMENTED();
return false;
}
-bool Socket::LeaveMulticast(
- intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
+bool Socket::LeaveMulticast(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr&,
+ int interfaceIndex) {
UNIMPLEMENTED();
return false;
}
diff --git a/runtime/bin/socket_linux.cc b/runtime/bin/socket_linux.cc
index fc0f1e4..2950728 100644
--- a/runtime/bin/socket_linux.cc
+++ b/runtime/bin/socket_linux.cc
@@ -10,15 +10,15 @@
#include "bin/socket.h"
#include "bin/socket_linux.h"
-#include <errno.h> // NOLINT
-#include <ifaddrs.h> // NOLINT
-#include <net/if.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <ifaddrs.h> // NOLINT
+#include <net/if.h> // NOLINT
#include <netinet/tcp.h> // NOLINT
-#include <stdio.h> // NOLINT
-#include <stdlib.h> // NOLINT
-#include <string.h> // NOLINT
-#include <sys/stat.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <stdio.h> // NOLINT
+#include <stdlib.h> // NOLINT
+#include <string.h> // NOLINT
+#include <sys/stat.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/fdutils.h"
#include "bin/file.h"
@@ -30,19 +30,19 @@
SocketAddress::SocketAddress(struct sockaddr* sa) {
ASSERT(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN);
- if (!Socket::FormatNumericAddress(
- *reinterpret_cast<RawAddr*>(sa), as_string_, INET6_ADDRSTRLEN)) {
+ if (!Socket::FormatNumericAddress(*reinterpret_cast<RawAddr*>(sa), as_string_,
+ INET6_ADDRSTRLEN)) {
as_string_[0] = 0;
}
socklen_t salen = GetAddrLength(*reinterpret_cast<RawAddr*>(sa));
- memmove(reinterpret_cast<void *>(&addr_), sa, salen);
+ memmove(reinterpret_cast<void*>(&addr_), sa, salen);
}
bool Socket::FormatNumericAddress(const RawAddr& addr, char* address, int len) {
socklen_t salen = SocketAddress::GetAddrLength(addr);
- return (NO_RETRY_EXPECTED(getnameinfo(
- &addr.addr, salen, address, len, NULL, 0, NI_NUMERICHOST) == 0));
+ return (NO_RETRY_EXPECTED(getnameinfo(&addr.addr, salen, address, len, NULL,
+ 0, NI_NUMERICHOST) == 0));
}
@@ -103,7 +103,7 @@
bool Socket::IsBindError(intptr_t error_number) {
return error_number == EADDRINUSE || error_number == EADDRNOTAVAIL ||
- error_number == EINVAL;
+ error_number == EINVAL;
}
@@ -125,8 +125,10 @@
}
-intptr_t Socket::RecvFrom(
- intptr_t fd, void* buffer, intptr_t num_bytes, RawAddr* addr) {
+intptr_t Socket::RecvFrom(intptr_t fd,
+ void* buffer,
+ intptr_t num_bytes,
+ RawAddr* addr) {
ASSERT(fd >= 0);
socklen_t addr_len = sizeof(addr->ss);
ssize_t read_bytes = TEMP_FAILURE_RETRY(
@@ -153,12 +155,14 @@
}
-intptr_t Socket::SendTo(
- intptr_t fd, const void* buffer, intptr_t num_bytes, const RawAddr& addr) {
+intptr_t Socket::SendTo(intptr_t fd,
+ const void* buffer,
+ intptr_t num_bytes,
+ const RawAddr& addr) {
ASSERT(fd >= 0);
- ssize_t written_bytes = TEMP_FAILURE_RETRY(
- sendto(fd, buffer, num_bytes, 0,
- &addr.addr, SocketAddress::GetAddrLength(addr)));
+ ssize_t written_bytes =
+ TEMP_FAILURE_RETRY(sendto(fd, buffer, num_bytes, 0, &addr.addr,
+ SocketAddress::GetAddrLength(addr)));
ASSERT(EAGAIN == EWOULDBLOCK);
if ((written_bytes == -1) && (errno == EWOULDBLOCK)) {
// If the would block we need to retry and therefore return 0 as
@@ -195,8 +199,8 @@
void Socket::GetError(intptr_t fd, OSError* os_error) {
int len = sizeof(errno);
int err = 0;
- VOID_NO_RETRY_EXPECTED(getsockopt(
- fd, SOL_SOCKET, SO_ERROR, &err, reinterpret_cast<socklen_t*>(&len)));
+ VOID_NO_RETRY_EXPECTED(getsockopt(fd, SOL_SOCKET, SO_ERROR, &err,
+ reinterpret_cast<socklen_t*>(&len)));
errno = err;
os_error->SetCodeAndMessage(OSError::kSystem, errno);
}
@@ -245,9 +249,8 @@
status = NO_RETRY_EXPECTED(getaddrinfo(host, 0, &hints, &info));
if (status != 0) {
ASSERT(*os_error == NULL);
- *os_error = new OSError(status,
- gai_strerror(status),
- OSError::kGetAddressInfo);
+ *os_error =
+ new OSError(status, gai_strerror(status), OSError::kGetAddressInfo);
return NULL;
}
}
@@ -275,19 +278,13 @@
intptr_t host_len,
OSError** os_error) {
ASSERT(host_len >= NI_MAXHOST);
- int status = NO_RETRY_EXPECTED(getnameinfo(
- &addr.addr,
- SocketAddress::GetAddrLength(addr),
- host,
- host_len,
- NULL,
- 0,
- NI_NAMEREQD));
+ int status = NO_RETRY_EXPECTED(
+ getnameinfo(&addr.addr, SocketAddress::GetAddrLength(addr), host,
+ host_len, NULL, 0, NI_NAMEREQD));
if (status != 0) {
ASSERT(*os_error == NULL);
- *os_error = new OSError(status,
- gai_strerror(status),
- OSError::kGetAddressInfo);
+ *os_error =
+ new OSError(status, gai_strerror(status), OSError::kGetAddressInfo);
return false;
}
return true;
@@ -300,8 +297,8 @@
result = NO_RETRY_EXPECTED(inet_pton(AF_INET, address, &addr->in.sin_addr));
} else {
ASSERT(type == SocketAddress::TYPE_IPV6);
- result = NO_RETRY_EXPECTED(
- inet_pton(AF_INET6, address, &addr->in6.sin6_addr));
+ result =
+ NO_RETRY_EXPECTED(inet_pton(AF_INET6, address, &addr->in6.sin6_addr));
}
return (result == 1);
}
@@ -311,8 +308,8 @@
intptr_t fd;
fd = NO_RETRY_EXPECTED(socket(addr.addr.sa_family,
- SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
- IPPROTO_UDP));
+ SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
+ IPPROTO_UDP));
if (fd < 0) {
return -1;
}
@@ -339,8 +336,8 @@
}
int family = ifa->ifa_addr->sa_family;
return ((lookup_family == family) ||
- (((lookup_family == AF_UNSPEC) &&
- ((family == AF_INET) || (family == AF_INET6)))));
+ (((lookup_family == AF_UNSPEC) &&
+ ((family == AF_INET) || (family == AF_INET6)))));
}
@@ -357,9 +354,8 @@
int status = NO_RETRY_EXPECTED(getifaddrs(&ifaddr));
if (status != 0) {
ASSERT(*os_error == NULL);
- *os_error = new OSError(status,
- gai_strerror(status),
- OSError::kGetAddressInfo);
+ *os_error =
+ new OSError(status, gai_strerror(status), OSError::kGetAddressInfo);
return NULL;
}
@@ -378,8 +374,9 @@
for (struct ifaddrs* ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ShouldIncludeIfaAddrs(ifa, lookup_family)) {
char* ifa_name = DartUtils::ScopedCopyCString(ifa->ifa_name);
- addresses->SetAt(i, new InterfaceSocketAddress(
- ifa->ifa_addr, ifa_name, if_nametoindex(ifa->ifa_name)));
+ addresses->SetAt(
+ i, new InterfaceSocketAddress(ifa->ifa_addr, ifa_name,
+ if_nametoindex(ifa->ifa_name)));
i++;
}
}
@@ -446,9 +443,9 @@
// On Linux a number of protocol errors should be treated as EAGAIN.
// These are the ones for TCP/IP.
return (error == EAGAIN) || (error == ENETDOWN) || (error == EPROTO) ||
- (error == ENOPROTOOPT) || (error == EHOSTDOWN) || (error == ENONET) ||
- (error == EHOSTUNREACH) || (error == EOPNOTSUPP) ||
- (error == ENETUNREACH);
+ (error == ENOPROTOOPT) || (error == EHOSTDOWN) || (error == ENONET) ||
+ (error == EHOSTUNREACH) || (error == EOPNOTSUPP) ||
+ (error == ENETUNREACH);
}
@@ -482,8 +479,8 @@
bool Socket::GetNoDelay(intptr_t fd, bool* enabled) {
int on;
socklen_t len = sizeof(on);
- int err = NO_RETRY_EXPECTED(getsockopt(
- fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<void *>(&on), &len));
+ int err = NO_RETRY_EXPECTED(getsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
+ reinterpret_cast<void*>(&on), &len));
if (err == 0) {
*enabled = (on == 1);
}
@@ -493,11 +490,9 @@
bool Socket::SetNoDelay(intptr_t fd, bool enabled) {
int on = enabled ? 1 : 0;
- return NO_RETRY_EXPECTED(setsockopt(fd,
- IPPROTO_TCP,
- TCP_NODELAY,
- reinterpret_cast<char *>(&on),
- sizeof(on))) == 0;
+ return NO_RETRY_EXPECTED(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
+ reinterpret_cast<char*>(&on),
+ sizeof(on))) == 0;
}
@@ -505,10 +500,10 @@
uint8_t on;
socklen_t len = sizeof(on);
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_LOOP : IPV6_MULTICAST_LOOP;
- if (NO_RETRY_EXPECTED(getsockopt(
- fd, level, optname, reinterpret_cast<char *>(&on), &len)) == 0) {
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_LOOP
+ : IPV6_MULTICAST_LOOP;
+ if (NO_RETRY_EXPECTED(getsockopt(fd, level, optname,
+ reinterpret_cast<char*>(&on), &len)) == 0) {
*enabled = (on == 1);
return true;
}
@@ -519,10 +514,11 @@
bool Socket::SetMulticastLoop(intptr_t fd, intptr_t protocol, bool enabled) {
int on = enabled ? 1 : 0;
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_LOOP : IPV6_MULTICAST_LOOP;
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_LOOP
+ : IPV6_MULTICAST_LOOP;
return NO_RETRY_EXPECTED(setsockopt(
- fd, level, optname, reinterpret_cast<char *>(&on), sizeof(on))) == 0;
+ fd, level, optname, reinterpret_cast<char*>(&on), sizeof(on))) ==
+ 0;
}
@@ -530,10 +526,10 @@
uint8_t v;
socklen_t len = sizeof(v);
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_TTL : IPV6_MULTICAST_HOPS;
- if (NO_RETRY_EXPECTED(getsockopt(
- fd, level, optname, reinterpret_cast<char *>(&v), &len)) == 0) {
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_TTL
+ : IPV6_MULTICAST_HOPS;
+ if (NO_RETRY_EXPECTED(getsockopt(fd, level, optname,
+ reinterpret_cast<char*>(&v), &len)) == 0) {
*value = v;
return true;
}
@@ -544,18 +540,18 @@
bool Socket::SetMulticastHops(intptr_t fd, intptr_t protocol, int value) {
int v = value;
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_TTL : IPV6_MULTICAST_HOPS;
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_TTL
+ : IPV6_MULTICAST_HOPS;
return NO_RETRY_EXPECTED(setsockopt(
- fd, level, optname, reinterpret_cast<char *>(&v), sizeof(v))) == 0;
+ fd, level, optname, reinterpret_cast<char*>(&v), sizeof(v))) == 0;
}
bool Socket::GetBroadcast(intptr_t fd, bool* enabled) {
int on;
socklen_t len = sizeof(on);
- int err = NO_RETRY_EXPECTED(getsockopt(
- fd, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<char *>(&on), &len));
+ int err = NO_RETRY_EXPECTED(getsockopt(fd, SOL_SOCKET, SO_BROADCAST,
+ reinterpret_cast<char*>(&on), &len));
if (err == 0) {
*enabled = (on == 1);
}
@@ -565,33 +561,35 @@
bool Socket::SetBroadcast(intptr_t fd, bool enabled) {
int on = enabled ? 1 : 0;
- return NO_RETRY_EXPECTED(setsockopt(fd,
- SOL_SOCKET,
- SO_BROADCAST,
- reinterpret_cast<char *>(&on),
- sizeof(on))) == 0;
+ return NO_RETRY_EXPECTED(setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
+ reinterpret_cast<char*>(&on),
+ sizeof(on))) == 0;
}
-bool Socket::JoinMulticast(
- intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
+bool Socket::JoinMulticast(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr&,
+ int interfaceIndex) {
int proto = addr.addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
struct group_req mreq;
mreq.gr_interface = interfaceIndex;
memmove(&mreq.gr_group, &addr.ss, SocketAddress::GetAddrLength(addr));
return NO_RETRY_EXPECTED(
- setsockopt(fd, proto, MCAST_JOIN_GROUP, &mreq, sizeof(mreq))) == 0;
+ setsockopt(fd, proto, MCAST_JOIN_GROUP, &mreq, sizeof(mreq))) == 0;
}
-bool Socket::LeaveMulticast(
- intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
+bool Socket::LeaveMulticast(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr&,
+ int interfaceIndex) {
int proto = addr.addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
struct group_req mreq;
mreq.gr_interface = interfaceIndex;
memmove(&mreq.gr_group, &addr.ss, SocketAddress::GetAddrLength(addr));
- return NO_RETRY_EXPECTED(
- setsockopt(fd, proto, MCAST_LEAVE_GROUP, &mreq, sizeof(mreq))) == 0;
+ return NO_RETRY_EXPECTED(setsockopt(fd, proto, MCAST_LEAVE_GROUP, &mreq,
+ sizeof(mreq))) == 0;
}
} // namespace bin
diff --git a/runtime/bin/socket_macos.cc b/runtime/bin/socket_macos.cc
index e54cc59..3e082eb 100644
--- a/runtime/bin/socket_macos.cc
+++ b/runtime/bin/socket_macos.cc
@@ -10,15 +10,15 @@
#include "bin/socket.h"
#include "bin/socket_macos.h"
-#include <errno.h> // NOLINT
-#include <ifaddrs.h> // NOLINT
-#include <net/if.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <ifaddrs.h> // NOLINT
+#include <net/if.h> // NOLINT
#include <netinet/tcp.h> // NOLINT
-#include <stdio.h> // NOLINT
-#include <stdlib.h> // NOLINT
-#include <string.h> // NOLINT
-#include <sys/stat.h> // NOLINT
-#include <unistd.h> // NOLINT
+#include <stdio.h> // NOLINT
+#include <stdlib.h> // NOLINT
+#include <string.h> // NOLINT
+#include <sys/stat.h> // NOLINT
+#include <unistd.h> // NOLINT
#include "bin/fdutils.h"
#include "bin/file.h"
@@ -29,19 +29,19 @@
SocketAddress::SocketAddress(struct sockaddr* sa) {
ASSERT(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN);
- if (!Socket::FormatNumericAddress(
- *reinterpret_cast<RawAddr*>(sa), as_string_, INET6_ADDRSTRLEN)) {
+ if (!Socket::FormatNumericAddress(*reinterpret_cast<RawAddr*>(sa), as_string_,
+ INET6_ADDRSTRLEN)) {
as_string_[0] = 0;
}
socklen_t salen = GetAddrLength(*reinterpret_cast<RawAddr*>(sa));
- memmove(reinterpret_cast<void *>(&addr_), sa, salen);
+ memmove(reinterpret_cast<void*>(&addr_), sa, salen);
}
bool Socket::FormatNumericAddress(const RawAddr& addr, char* address, int len) {
socklen_t salen = SocketAddress::GetAddrLength(addr);
- return (NO_RETRY_EXPECTED(getnameinfo(
- &addr.addr, salen, address, len, NULL, 0, NI_NUMERICHOST)) == 0);
+ return (NO_RETRY_EXPECTED(getnameinfo(&addr.addr, salen, address, len, NULL,
+ 0, NI_NUMERICHOST)) == 0);
}
@@ -104,7 +104,7 @@
bool Socket::IsBindError(intptr_t error_number) {
return error_number == EADDRINUSE || error_number == EADDRNOTAVAIL ||
- error_number == EINVAL;
+ error_number == EINVAL;
}
@@ -126,8 +126,10 @@
}
-intptr_t Socket::RecvFrom(
- intptr_t fd, void* buffer, intptr_t num_bytes, RawAddr* addr) {
+intptr_t Socket::RecvFrom(intptr_t fd,
+ void* buffer,
+ intptr_t num_bytes,
+ RawAddr* addr) {
ASSERT(fd >= 0);
socklen_t addr_len = sizeof(addr->ss);
ssize_t read_bytes = TEMP_FAILURE_RETRY(
@@ -154,12 +156,14 @@
}
-intptr_t Socket::SendTo(
- intptr_t fd, const void* buffer, intptr_t num_bytes, const RawAddr& addr) {
+intptr_t Socket::SendTo(intptr_t fd,
+ const void* buffer,
+ intptr_t num_bytes,
+ const RawAddr& addr) {
ASSERT(fd >= 0);
- ssize_t written_bytes = TEMP_FAILURE_RETRY(
- sendto(fd, buffer, num_bytes, 0,
- &addr.addr, SocketAddress::GetAddrLength(addr)));
+ ssize_t written_bytes =
+ TEMP_FAILURE_RETRY(sendto(fd, buffer, num_bytes, 0, &addr.addr,
+ SocketAddress::GetAddrLength(addr)));
ASSERT(EAGAIN == EWOULDBLOCK);
if ((written_bytes == -1) && (errno == EWOULDBLOCK)) {
// If the would block we need to retry and therefore return 0 as
@@ -195,10 +199,7 @@
void Socket::GetError(intptr_t fd, OSError* os_error) {
int len = sizeof(errno);
- getsockopt(fd,
- SOL_SOCKET,
- SO_ERROR,
- &errno,
+ getsockopt(fd, SOL_SOCKET, SO_ERROR, &errno,
reinterpret_cast<socklen_t*>(&len));
os_error->SetCodeAndMessage(OSError::kSystem, errno);
}
@@ -242,9 +243,8 @@
int status = getaddrinfo(host, 0, &hints, &info);
if (status != 0) {
ASSERT(*os_error == NULL);
- *os_error = new OSError(status,
- gai_strerror(status),
- OSError::kGetAddressInfo);
+ *os_error =
+ new OSError(status, gai_strerror(status), OSError::kGetAddressInfo);
return NULL;
}
intptr_t count = 0;
@@ -271,19 +271,13 @@
intptr_t host_len,
OSError** os_error) {
ASSERT(host_len >= NI_MAXHOST);
- int status = NO_RETRY_EXPECTED(getnameinfo(
- &addr.addr,
- SocketAddress::GetAddrLength(addr),
- host,
- host_len,
- NULL,
- 0,
- NI_NAMEREQD));
+ int status = NO_RETRY_EXPECTED(
+ getnameinfo(&addr.addr, SocketAddress::GetAddrLength(addr), host,
+ host_len, NULL, 0, NI_NAMEREQD));
if (status != 0) {
ASSERT(*os_error == NULL);
- *os_error = new OSError(status,
- gai_strerror(status),
- OSError::kGetAddressInfo);
+ *os_error =
+ new OSError(status, gai_strerror(status), OSError::kGetAddressInfo);
return false;
}
return true;
@@ -336,8 +330,8 @@
}
int family = ifa->ifa_addr->sa_family;
return ((lookup_family == family) ||
- ((lookup_family == AF_UNSPEC) &&
- ((family == AF_INET) || (family == AF_INET6))));
+ ((lookup_family == AF_UNSPEC) &&
+ ((family == AF_INET) || (family == AF_INET6))));
}
@@ -354,9 +348,8 @@
int status = getifaddrs(&ifaddr);
if (status != 0) {
ASSERT(*os_error == NULL);
- *os_error = new OSError(status,
- gai_strerror(status),
- OSError::kGetAddressInfo);
+ *os_error =
+ new OSError(status, gai_strerror(status), OSError::kGetAddressInfo);
return NULL;
}
@@ -373,8 +366,9 @@
for (struct ifaddrs* ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ShouldIncludeIfaAddrs(ifa, lookup_family)) {
char* ifa_name = DartUtils::ScopedCopyCString(ifa->ifa_name);
- addresses->SetAt(i, new InterfaceSocketAddress(
- ifa->ifa_addr, ifa_name, if_nametoindex(ifa->ifa_name)));
+ addresses->SetAt(
+ i, new InterfaceSocketAddress(ifa->ifa_addr, ifa_name,
+ if_nametoindex(ifa->ifa_name)));
i++;
}
}
@@ -469,11 +463,8 @@
bool Socket::GetNoDelay(intptr_t fd, bool* enabled) {
int on;
socklen_t len = sizeof(on);
- int err = NO_RETRY_EXPECTED(getsockopt(fd,
- IPPROTO_TCP,
- TCP_NODELAY,
- reinterpret_cast<void *>(&on),
- &len));
+ int err = NO_RETRY_EXPECTED(getsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
+ reinterpret_cast<void*>(&on), &len));
if (err == 0) {
*enabled = (on == 1);
}
@@ -483,10 +474,8 @@
bool Socket::SetNoDelay(intptr_t fd, bool enabled) {
int on = enabled ? 1 : 0;
- return NO_RETRY_EXPECTED(setsockopt(fd,
- IPPROTO_TCP,
- TCP_NODELAY,
- reinterpret_cast<char *>(&on),
+ return NO_RETRY_EXPECTED(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
+ reinterpret_cast<char*>(&on),
sizeof(on))) == 0;
}
@@ -495,13 +484,10 @@
uint8_t on;
socklen_t len = sizeof(on);
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_LOOP : IPV6_MULTICAST_LOOP;
- if (NO_RETRY_EXPECTED(getsockopt(fd,
- level,
- optname,
- reinterpret_cast<char *>(&on),
- &len)) == 0) {
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_LOOP
+ : IPV6_MULTICAST_LOOP;
+ if (NO_RETRY_EXPECTED(getsockopt(fd, level, optname,
+ reinterpret_cast<char*>(&on), &len)) == 0) {
*enabled = (on == 1);
return true;
}
@@ -512,13 +498,11 @@
bool Socket::SetMulticastLoop(intptr_t fd, intptr_t protocol, bool enabled) {
u_int on = enabled ? 1 : 0;
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_LOOP : IPV6_MULTICAST_LOOP;
- return NO_RETRY_EXPECTED(setsockopt(fd,
- level,
- optname,
- reinterpret_cast<char *>(&on),
- sizeof(on))) == 0;
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_LOOP
+ : IPV6_MULTICAST_LOOP;
+ return NO_RETRY_EXPECTED(setsockopt(
+ fd, level, optname, reinterpret_cast<char*>(&on), sizeof(on))) ==
+ 0;
}
@@ -526,13 +510,10 @@
uint8_t v;
socklen_t len = sizeof(v);
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_TTL : IPV6_MULTICAST_HOPS;
- if (NO_RETRY_EXPECTED(getsockopt(fd,
- level,
- optname,
- reinterpret_cast<char *>(&v),
- &len)) == 0) {
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_TTL
+ : IPV6_MULTICAST_HOPS;
+ if (NO_RETRY_EXPECTED(getsockopt(fd, level, optname,
+ reinterpret_cast<char*>(&v), &len)) == 0) {
*value = v;
return true;
}
@@ -543,24 +524,18 @@
bool Socket::SetMulticastHops(intptr_t fd, intptr_t protocol, int value) {
int v = value;
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_TTL : IPV6_MULTICAST_HOPS;
- return NO_RETRY_EXPECTED(setsockopt(fd,
- level,
- optname,
- reinterpret_cast<char *>(&v),
- sizeof(v))) == 0;
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_TTL
+ : IPV6_MULTICAST_HOPS;
+ return NO_RETRY_EXPECTED(setsockopt(
+ fd, level, optname, reinterpret_cast<char*>(&v), sizeof(v))) == 0;
}
bool Socket::GetBroadcast(intptr_t fd, bool* enabled) {
int on;
socklen_t len = sizeof(on);
- int err = NO_RETRY_EXPECTED(getsockopt(fd,
- SOL_SOCKET,
- SO_BROADCAST,
- reinterpret_cast<char *>(&on),
- &len));
+ int err = NO_RETRY_EXPECTED(getsockopt(fd, SOL_SOCKET, SO_BROADCAST,
+ reinterpret_cast<char*>(&on), &len));
if (err == 0) {
*enabled = (on == 1);
}
@@ -570,10 +545,8 @@
bool Socket::SetBroadcast(intptr_t fd, bool enabled) {
int on = enabled ? 1 : 0;
- return NO_RETRY_EXPECTED(setsockopt(fd,
- SOL_SOCKET,
- SO_BROADCAST,
- reinterpret_cast<char *>(&on),
+ return NO_RETRY_EXPECTED(setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
+ reinterpret_cast<char*>(&on),
sizeof(on))) == 0;
}
@@ -586,32 +559,29 @@
if (addr.addr.sa_family == AF_INET) {
ASSERT(interface.addr.sa_family == AF_INET);
struct ip_mreq mreq;
- memmove(&mreq.imr_multiaddr,
- &addr.in.sin_addr,
+ memmove(&mreq.imr_multiaddr, &addr.in.sin_addr,
SocketAddress::GetInAddrLength(addr));
- memmove(&mreq.imr_interface,
- &interface.in.sin_addr,
+ memmove(&mreq.imr_interface, &interface.in.sin_addr,
SocketAddress::GetInAddrLength(interface));
if (join) {
- return NO_RETRY_EXPECTED(setsockopt(
- fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq))) == 0;
+ return NO_RETRY_EXPECTED(setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
+ &mreq, sizeof(mreq))) == 0;
} else {
- return NO_RETRY_EXPECTED(setsockopt(
- fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq))) == 0;
+ return NO_RETRY_EXPECTED(setsockopt(fd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
+ &mreq, sizeof(mreq))) == 0;
}
} else {
ASSERT(addr.addr.sa_family == AF_INET6);
struct ipv6_mreq mreq;
- memmove(&mreq.ipv6mr_multiaddr,
- &addr.in6.sin6_addr,
+ memmove(&mreq.ipv6mr_multiaddr, &addr.in6.sin6_addr,
SocketAddress::GetInAddrLength(addr));
mreq.ipv6mr_interface = interfaceIndex;
if (join) {
- return NO_RETRY_EXPECTED(setsockopt(
- fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof(mreq))) == 0;
+ return NO_RETRY_EXPECTED(setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
+ &mreq, sizeof(mreq))) == 0;
} else {
- return NO_RETRY_EXPECTED(setsockopt(
- fd, IPPROTO_IPV6, IPV6_LEAVE_GROUP, &mreq, sizeof(mreq))) == 0;
+ return NO_RETRY_EXPECTED(setsockopt(fd, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
+ &mreq, sizeof(mreq))) == 0;
}
}
}
diff --git a/runtime/bin/socket_unsupported.cc b/runtime/bin/socket_unsupported.cc
index d3ecf1e..39b2f57 100644
--- a/runtime/bin/socket_unsupported.cc
+++ b/runtime/bin/socket_unsupported.cc
@@ -16,146 +16,146 @@
bool short_socket_write = false;
void FUNCTION_NAME(InternetAddress_Parse)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(NetworkInterface_ListSupported)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_CreateConnect)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_CreateBindConnect)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_IsBindError)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_CreateBindDatagram)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_Available)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_Read)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_RecvFrom)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_WriteList)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_SendTo)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_GetPort)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_GetRemotePeer)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_GetError)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_GetType)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_GetStdioHandle)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_GetSocketId)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_SetSocketId)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(ServerSocket_CreateBindListen)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(ServerSocket_Accept)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_GetOption)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_SetOption)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_JoinMulticast)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
void FUNCTION_NAME(Socket_LeaveMulticast)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Sockets unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Sockets unsupported on this platform"));
}
} // namespace bin
diff --git a/runtime/bin/socket_win.cc b/runtime/bin/socket_win.cc
index 1dce52e..55cc107 100644
--- a/runtime/bin/socket_win.cc
+++ b/runtime/bin/socket_win.cc
@@ -33,8 +33,7 @@
if (err != 0) {
as_string_[0] = 0;
}
- memmove(reinterpret_cast<void *>(&addr_),
- sockaddr,
+ memmove(reinterpret_cast<void*>(&addr_), sockaddr,
SocketAddress::GetAddrLength(*raw));
}
@@ -43,11 +42,7 @@
socklen_t salen = SocketAddress::GetAddrLength(addr);
DWORD l = len;
RawAddr& raw = const_cast<RawAddr&>(addr);
- return WSAAddressToStringA(&raw.addr,
- salen,
- NULL,
- address,
- &l) != 0;
+ return WSAAddressToStringA(&raw.addr, salen, NULL, address, &l) != 0;
}
@@ -83,8 +78,10 @@
}
-intptr_t Socket::RecvFrom(
- intptr_t fd, void* buffer, intptr_t num_bytes, RawAddr* addr) {
+intptr_t Socket::RecvFrom(intptr_t fd,
+ void* buffer,
+ intptr_t num_bytes,
+ RawAddr* addr) {
Handle* handle = reinterpret_cast<Handle*>(fd);
socklen_t addr_len = sizeof(addr->ss);
return handle->RecvFrom(buffer, num_bytes, &addr->addr, addr_len);
@@ -97,12 +94,14 @@
}
-intptr_t Socket::SendTo(
- intptr_t fd, const void* buffer, intptr_t num_bytes, const RawAddr& addr) {
+intptr_t Socket::SendTo(intptr_t fd,
+ const void* buffer,
+ intptr_t num_bytes,
+ const RawAddr& addr) {
Handle* handle = reinterpret_cast<Handle*>(fd);
RawAddr& raw = const_cast<RawAddr&>(addr);
- return handle->SendTo(
- buffer, num_bytes, &raw.addr, SocketAddress::GetAddrLength(addr));
+ return handle->SendTo(buffer, num_bytes, &raw.addr,
+ SocketAddress::GetAddrLength(addr));
}
@@ -111,7 +110,7 @@
SocketHandle* socket_handle = reinterpret_cast<SocketHandle*>(fd);
RawAddr raw;
socklen_t size = sizeof(raw);
- if (getsockname(socket_handle->socket(), &raw.addr, &size) == SOCKET_ERROR) {
+ if (getsockname(socket_handle->socket(), &raw.addr, &size) == SOCKET_ERROR) {
return 0;
}
return SocketAddress::GetAddrPort(raw);
@@ -143,10 +142,7 @@
linger l;
l.l_onoff = 1;
l.l_linger = 10;
- int status = setsockopt(s,
- SOL_SOCKET,
- SO_LINGER,
- reinterpret_cast<char*>(&l),
+ int status = setsockopt(s, SOL_SOCKET, SO_LINGER, reinterpret_cast<char*>(&l),
sizeof(l));
if (status != NO_ERROR) {
FATAL("Failed setting SO_LINGER on socket");
@@ -157,14 +153,15 @@
}
-static intptr_t Connect(
- intptr_t fd, const RawAddr& addr, const RawAddr& bind_addr) {
+static intptr_t Connect(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr& bind_addr) {
ASSERT(reinterpret_cast<Handle*>(fd)->is_client_socket());
ClientSocket* handle = reinterpret_cast<ClientSocket*>(fd);
SOCKET s = handle->socket();
- int status = bind(
- s, &bind_addr.addr, SocketAddress::GetAddrLength(bind_addr));
+ int status =
+ bind(s, &bind_addr.addr, SocketAddress::GetAddrLength(bind_addr));
if (status != NO_ERROR) {
int rc = WSAGetLastError();
handle->mark_closed(); // Destructor asserts that socket is marked closed.
@@ -177,28 +174,17 @@
LPFN_CONNECTEX connectEx = NULL;
GUID guid_connect_ex = WSAID_CONNECTEX;
DWORD bytes;
- status = WSAIoctl(s,
- SIO_GET_EXTENSION_FUNCTION_POINTER,
- &guid_connect_ex,
- sizeof(guid_connect_ex),
- &connectEx,
- sizeof(connectEx),
- &bytes,
- NULL,
- NULL);
+ status = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid_connect_ex,
+ sizeof(guid_connect_ex), &connectEx, sizeof(connectEx),
+ &bytes, NULL, NULL);
DWORD rc;
if (status != SOCKET_ERROR) {
handle->EnsureInitialized(EventHandler::delegate());
OverlappedBuffer* overlapped = OverlappedBuffer::AllocateConnectBuffer();
- status = connectEx(s,
- &addr.addr,
- SocketAddress::GetAddrLength(addr),
- NULL,
- 0,
- NULL,
- overlapped->GetCleanOverlapped());
+ status = connectEx(s, &addr.addr, SocketAddress::GetAddrLength(addr), NULL,
+ 0, NULL, overlapped->GetCleanOverlapped());
if (status == TRUE) {
@@ -252,7 +238,7 @@
bool Socket::IsBindError(intptr_t error_number) {
return error_number == WSAEADDRINUSE || error_number == WSAEADDRNOTAVAIL ||
- error_number == WSAEINVAL;
+ error_number == WSAEINVAL;
}
@@ -265,10 +251,14 @@
int Socket::GetType(intptr_t fd) {
Handle* handle = reinterpret_cast<Handle*>(fd);
switch (GetFileType(handle->handle())) {
- case FILE_TYPE_CHAR: return File::kTerminal;
- case FILE_TYPE_PIPE: return File::kPipe;
- case FILE_TYPE_DISK: return File::kFile;
- default: return GetLastError == NO_ERROR ? File::kOther : -1;
+ case FILE_TYPE_CHAR:
+ return File::kTerminal;
+ case FILE_TYPE_PIPE:
+ return File::kPipe;
+ case FILE_TYPE_DISK:
+ return File::kFile;
+ default:
+ return GetLastError == NO_ERROR ? File::kOther : -1;
}
}
@@ -350,13 +340,8 @@
intptr_t host_len,
OSError** os_error) {
ASSERT(host_len >= NI_MAXHOST);
- int status = getnameinfo(&addr.addr,
- SocketAddress::GetAddrLength(addr),
- host,
- host_len,
- NULL,
- 0,
- NI_NAMEREQD);
+ int status = getnameinfo(&addr.addr, SocketAddress::GetAddrLength(addr), host,
+ host_len, NULL, 0, NI_NAMEREQD);
if (status != 0) {
ASSERT(*os_error == NULL);
DWORD error_code = WSAGetLastError();
@@ -390,11 +375,8 @@
int status;
if (reuseAddress) {
BOOL optval = true;
- status = setsockopt(s,
- SOL_SOCKET,
- SO_REUSEADDR,
- reinterpret_cast<const char*>(&optval),
- sizeof(optval));
+ status = setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
+ reinterpret_cast<const char*>(&optval), sizeof(optval));
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
closesocket(s);
@@ -403,7 +385,7 @@
}
}
- status = bind(s, &addr.addr, SocketAddress::GetAddrLength(addr));
+ status = bind(s, &addr.addr, SocketAddress::GetAddrLength(addr));
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
closesocket(s);
@@ -428,24 +410,17 @@
Initialize();
ULONG size = 0;
- DWORD flags = GAA_FLAG_SKIP_ANYCAST |
- GAA_FLAG_SKIP_MULTICAST |
+ DWORD flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST |
GAA_FLAG_SKIP_DNS_SERVER;
// Query the size needed.
- int status = GetAdaptersAddresses(SocketAddress::FromType(type),
- flags,
- NULL,
- NULL,
- &size);
+ int status = GetAdaptersAddresses(SocketAddress::FromType(type), flags, NULL,
+ NULL, &size);
IP_ADAPTER_ADDRESSES* addrs = NULL;
if (status == ERROR_BUFFER_OVERFLOW) {
addrs = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(malloc(size));
// Get the addresses now we have the right buffer.
- status = GetAdaptersAddresses(SocketAddress::FromType(type),
- flags,
- NULL,
- addrs,
- &size);
+ status = GetAdaptersAddresses(SocketAddress::FromType(type), flags, NULL,
+ addrs, &size);
}
if (status != NO_ERROR) {
ASSERT(*os_error == NULL);
@@ -456,8 +431,8 @@
}
intptr_t count = 0;
for (IP_ADAPTER_ADDRESSES* a = addrs; a != NULL; a = a->Next) {
- for (IP_ADAPTER_UNICAST_ADDRESS* u = a->FirstUnicastAddress;
- u != NULL; u = u->Next) {
+ for (IP_ADAPTER_UNICAST_ADDRESS* u = a->FirstUnicastAddress; u != NULL;
+ u = u->Next) {
count++;
}
}
@@ -465,12 +440,12 @@
new AddressList<InterfaceSocketAddress>(count);
intptr_t i = 0;
for (IP_ADAPTER_ADDRESSES* a = addrs; a != NULL; a = a->Next) {
- for (IP_ADAPTER_UNICAST_ADDRESS* u = a->FirstUnicastAddress;
- u != NULL; u = u->Next) {
- addresses->SetAt(i, new InterfaceSocketAddress(
- u->Address.lpSockaddr,
- StringUtilsWin::WideToUtf8(a->FriendlyName),
- a->Ipv6IfIndex));
+ for (IP_ADAPTER_UNICAST_ADDRESS* u = a->FirstUnicastAddress; u != NULL;
+ u = u->Next) {
+ addresses->SetAt(
+ i, new InterfaceSocketAddress(
+ u->Address.lpSockaddr,
+ StringUtilsWin::WideToUtf8(a->FriendlyName), a->Ipv6IfIndex));
i++;
}
}
@@ -488,11 +463,9 @@
}
BOOL optval = true;
- int status = setsockopt(s,
- SOL_SOCKET,
- SO_EXCLUSIVEADDRUSE,
- reinterpret_cast<const char*>(&optval),
- sizeof(optval));
+ int status =
+ setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
+ reinterpret_cast<const char*>(&optval), sizeof(optval));
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
closesocket(s);
@@ -502,11 +475,8 @@
if (addr.ss.ss_family == AF_INET6) {
optval = v6_only;
- setsockopt(s,
- IPPROTO_IPV6,
- IPV6_V6ONLY,
- reinterpret_cast<const char*>(&optval),
- sizeof(optval));
+ setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
+ reinterpret_cast<const char*>(&optval), sizeof(optval));
}
status = bind(s, &addr.addr, SocketAddress::GetAddrLength(addr));
@@ -576,11 +546,8 @@
SocketHandle* handle = reinterpret_cast<SocketHandle*>(fd);
int on;
socklen_t len = sizeof(on);
- int err = getsockopt(handle->socket(),
- IPPROTO_TCP,
- TCP_NODELAY,
- reinterpret_cast<char *>(&on),
- &len);
+ int err = getsockopt(handle->socket(), IPPROTO_TCP, TCP_NODELAY,
+ reinterpret_cast<char*>(&on), &len);
if (err == 0) {
*enabled = (on == 1);
}
@@ -591,11 +558,8 @@
bool Socket::SetNoDelay(intptr_t fd, bool enabled) {
SocketHandle* handle = reinterpret_cast<SocketHandle*>(fd);
int on = enabled ? 1 : 0;
- return setsockopt(handle->socket(),
- IPPROTO_TCP,
- TCP_NODELAY,
- reinterpret_cast<char *>(&on),
- sizeof(on)) == 0;
+ return setsockopt(handle->socket(), IPPROTO_TCP, TCP_NODELAY,
+ reinterpret_cast<char*>(&on), sizeof(on)) == 0;
}
@@ -604,12 +568,9 @@
uint8_t on;
socklen_t len = sizeof(on);
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_LOOP : IPV6_MULTICAST_LOOP;
- if (getsockopt(handle->socket(),
- level,
- optname,
- reinterpret_cast<char *>(&on),
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_LOOP
+ : IPV6_MULTICAST_LOOP;
+ if (getsockopt(handle->socket(), level, optname, reinterpret_cast<char*>(&on),
&len) == 0) {
*enabled = (on == 1);
return true;
@@ -622,13 +583,10 @@
SocketHandle* handle = reinterpret_cast<SocketHandle*>(fd);
int on = enabled ? 1 : 0;
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_LOOP : IPV6_MULTICAST_LOOP;
- return setsockopt(handle->socket(),
- level,
- optname,
- reinterpret_cast<char *>(&on),
- sizeof(on)) == 0;
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_LOOP
+ : IPV6_MULTICAST_LOOP;
+ return setsockopt(handle->socket(), level, optname,
+ reinterpret_cast<char*>(&on), sizeof(on)) == 0;
}
@@ -637,12 +595,9 @@
uint8_t v;
socklen_t len = sizeof(v);
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_TTL : IPV6_MULTICAST_HOPS;
- if (getsockopt(handle->socket(),
- level,
- optname,
- reinterpret_cast<char *>(&v),
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_TTL
+ : IPV6_MULTICAST_HOPS;
+ if (getsockopt(handle->socket(), level, optname, reinterpret_cast<char*>(&v),
&len) == 0) {
*value = v;
return true;
@@ -655,13 +610,10 @@
SocketHandle* handle = reinterpret_cast<SocketHandle*>(fd);
int v = value;
int level = protocol == SocketAddress::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
- int optname = protocol == SocketAddress::TYPE_IPV4
- ? IP_MULTICAST_TTL : IPV6_MULTICAST_HOPS;
- return setsockopt(handle->socket(),
- level,
- optname,
- reinterpret_cast<char *>(&v),
- sizeof(v)) == 0;
+ int optname = protocol == SocketAddress::TYPE_IPV4 ? IP_MULTICAST_TTL
+ : IPV6_MULTICAST_HOPS;
+ return setsockopt(handle->socket(), level, optname,
+ reinterpret_cast<char*>(&v), sizeof(v)) == 0;
}
@@ -669,11 +621,8 @@
SocketHandle* handle = reinterpret_cast<SocketHandle*>(fd);
int on;
socklen_t len = sizeof(on);
- int err = getsockopt(handle->socket(),
- SOL_SOCKET,
- SO_BROADCAST,
- reinterpret_cast<char *>(&on),
- &len);
+ int err = getsockopt(handle->socket(), SOL_SOCKET, SO_BROADCAST,
+ reinterpret_cast<char*>(&on), &len);
if (err == 0) {
*enabled = (on == 1);
}
@@ -684,41 +633,36 @@
bool Socket::SetBroadcast(intptr_t fd, bool enabled) {
SocketHandle* handle = reinterpret_cast<SocketHandle*>(fd);
int on = enabled ? 1 : 0;
- return setsockopt(handle->socket(),
- SOL_SOCKET,
- SO_BROADCAST,
- reinterpret_cast<char *>(&on),
- sizeof(on)) == 0;
+ return setsockopt(handle->socket(), SOL_SOCKET, SO_BROADCAST,
+ reinterpret_cast<char*>(&on), sizeof(on)) == 0;
}
-bool Socket::JoinMulticast(
- intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
+bool Socket::JoinMulticast(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr&,
+ int interfaceIndex) {
SocketHandle* handle = reinterpret_cast<SocketHandle*>(fd);
int proto = addr.addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
struct group_req mreq;
mreq.gr_interface = interfaceIndex;
memmove(&mreq.gr_group, &addr.ss, SocketAddress::GetAddrLength(addr));
- return setsockopt(handle->socket(),
- proto,
- MCAST_JOIN_GROUP,
- reinterpret_cast<char *>(&mreq),
- sizeof(mreq)) == 0;
+ return setsockopt(handle->socket(), proto, MCAST_JOIN_GROUP,
+ reinterpret_cast<char*>(&mreq), sizeof(mreq)) == 0;
}
-bool Socket::LeaveMulticast(
- intptr_t fd, const RawAddr& addr, const RawAddr&, int interfaceIndex) {
+bool Socket::LeaveMulticast(intptr_t fd,
+ const RawAddr& addr,
+ const RawAddr&,
+ int interfaceIndex) {
SocketHandle* handle = reinterpret_cast<SocketHandle*>(fd);
int proto = addr.addr.sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
struct group_req mreq;
mreq.gr_interface = interfaceIndex;
memmove(&mreq.gr_group, &addr.ss, SocketAddress::GetAddrLength(addr));
- return setsockopt(handle->socket(),
- proto,
- MCAST_LEAVE_GROUP,
- reinterpret_cast<char *>(&mreq),
- sizeof(mreq)) == 0;
+ return setsockopt(handle->socket(), proto, MCAST_LEAVE_GROUP,
+ reinterpret_cast<char*>(&mreq), sizeof(mreq)) == 0;
}
} // namespace bin
diff --git a/runtime/bin/stdio_android.cc b/runtime/bin/stdio_android.cc
index 019efeb..35d83e5 100644
--- a/runtime/bin/stdio_android.cc
+++ b/runtime/bin/stdio_android.cc
@@ -9,9 +9,9 @@
#include "bin/stdio.h"
-#include <errno.h> // NOLINT
+#include <errno.h> // NOLINT
#include <sys/ioctl.h> // NOLINT
-#include <termios.h> // NOLINT
+#include <termios.h> // NOLINT
#include "bin/fdutils.h"
#include "platform/signal_blocker.h"
diff --git a/runtime/bin/stdio_linux.cc b/runtime/bin/stdio_linux.cc
index 0634fa4..280c75f 100644
--- a/runtime/bin/stdio_linux.cc
+++ b/runtime/bin/stdio_linux.cc
@@ -9,9 +9,9 @@
#include "bin/stdio.h"
-#include <errno.h> // NOLINT
+#include <errno.h> // NOLINT
#include <sys/ioctl.h> // NOLINT
-#include <termios.h> // NOLINT
+#include <termios.h> // NOLINT
#include "bin/fdutils.h"
#include "platform/signal_blocker.h"
diff --git a/runtime/bin/stdio_macos.cc b/runtime/bin/stdio_macos.cc
index d22f192..a8bd159 100644
--- a/runtime/bin/stdio_macos.cc
+++ b/runtime/bin/stdio_macos.cc
@@ -9,9 +9,9 @@
#include "bin/stdio.h"
-#include <errno.h> // NOLINT
+#include <errno.h> // NOLINT
#include <sys/ioctl.h> // NOLINT
-#include <termios.h> // NOLINT
+#include <termios.h> // NOLINT
#include "bin/fdutils.h"
#include "platform/signal_blocker.h"
diff --git a/runtime/bin/stdio_unsupported.cc b/runtime/bin/stdio_unsupported.cc
index 1e6c213..1482f91 100644
--- a/runtime/bin/stdio_unsupported.cc
+++ b/runtime/bin/stdio_unsupported.cc
@@ -12,38 +12,38 @@
namespace bin {
void FUNCTION_NAME(Stdin_ReadByte)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Stdin unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Stdin unsupported on this platform"));
}
void FUNCTION_NAME(Stdin_GetEchoMode)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Stdin unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Stdin unsupported on this platform"));
}
void FUNCTION_NAME(Stdin_SetEchoMode)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Stdin unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Stdin unsupported on this platform"));
}
void FUNCTION_NAME(Stdin_GetLineMode)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Stdin unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Stdin unsupported on this platform"));
}
void FUNCTION_NAME(Stdin_SetLineMode)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Stdin unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Stdin unsupported on this platform"));
}
void FUNCTION_NAME(Stdout_GetTerminalSize)(Dart_NativeArguments args) {
- Dart_ThrowException(DartUtils::NewDartArgumentError(
- "Stdout unsupported on this platform"));
+ Dart_ThrowException(
+ DartUtils::NewDartArgumentError("Stdout unsupported on this platform"));
}
} // namespace bin
diff --git a/runtime/bin/test_extension_dllmain_win.cc b/runtime/bin/test_extension_dllmain_win.cc
index ba2199a..93b66d6 100644
--- a/runtime/bin/test_extension_dllmain_win.cc
+++ b/runtime/bin/test_extension_dllmain_win.cc
@@ -8,9 +8,7 @@
#define WIN32_LEAN_AND_MEAN
#include <windows.h> // NOLINT
-BOOL APIENTRY DllMain(HMODULE module,
- DWORD reason,
- LPVOID reserved) {
+BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) {
return true;
}
diff --git a/runtime/bin/thread.h b/runtime/bin/thread.h
index 365cd95..e33e7f2 100644
--- a/runtime/bin/thread.h
+++ b/runtime/bin/thread.h
@@ -38,7 +38,7 @@
static const ThreadLocalKey kUnsetThreadLocalKey;
static const ThreadId kInvalidThreadId;
- typedef void (*ThreadStartFunction) (uword parameter);
+ typedef void (*ThreadStartFunction)(uword parameter);
// Start a thread running the specified function. Returns 0 if the
// thread started successfuly and a system specific error code if
@@ -83,10 +83,7 @@
class Monitor {
public:
- enum WaitResult {
- kNotified,
- kTimedOut
- };
+ enum WaitResult { kNotified, kTimedOut };
static const int64_t kNoTimeout = 0;
diff --git a/runtime/bin/thread_android.cc b/runtime/bin/thread_android.cc
index ce27ea3..cee224d 100644
--- a/runtime/bin/thread_android.cc
+++ b/runtime/bin/thread_android.cc
@@ -8,7 +8,7 @@
#include "bin/thread.h"
#include "bin/thread_android.h"
-#include <errno.h> // NOLINT
+#include <errno.h> // NOLINT
#include <sys/time.h> // NOLINT
#include "platform/assert.h"
@@ -17,29 +17,29 @@
namespace dart {
namespace bin {
-#define VALIDATE_PTHREAD_RESULT(result) \
- if (result != 0) { \
- const int kBufferSize = 1024; \
- char error_message[kBufferSize]; \
- Utils::StrError(result, error_message, kBufferSize); \
- FATAL2("pthread error: %d (%s)", result, error_message); \
+#define VALIDATE_PTHREAD_RESULT(result) \
+ if (result != 0) { \
+ const int kBufferSize = 1024; \
+ char error_message[kBufferSize]; \
+ Utils::StrError(result, error_message, kBufferSize); \
+ FATAL2("pthread error: %d (%s)", result, error_message); \
}
#ifdef DEBUG
-#define RETURN_ON_PTHREAD_FAILURE(result) \
- if (result != 0) { \
- const int kBufferSize = 1024; \
- char error_message[kBufferSize]; \
- Utils::StrError(result, error_message, kBufferSize); \
- fprintf(stderr, "%s:%d: pthread error: %d (%s)\n", \
- __FILE__, __LINE__, result, error_message); \
- return result; \
+#define RETURN_ON_PTHREAD_FAILURE(result) \
+ if (result != 0) { \
+ const int kBufferSize = 1024; \
+ char error_message[kBufferSize]; \
+ Utils::StrError(result, error_message, kBufferSize); \
+ fprintf(stderr, "%s:%d: pthread error: %d (%s)\n", __FILE__, __LINE__, \
+ result, error_message); \
+ return result; \
}
#else
-#define RETURN_ON_PTHREAD_FAILURE(result) \
- if (result != 0) { \
- return result; \
+#define RETURN_ON_PTHREAD_FAILURE(result) \
+ if (result != 0) { \
+ return result; \
}
#endif
@@ -61,8 +61,7 @@
class ThreadStartData {
public:
- ThreadStartData(Thread::ThreadStartFunction function,
- uword parameter)
+ ThreadStartData(Thread::ThreadStartFunction function, uword parameter)
: function_(function), parameter_(parameter) {}
Thread::ThreadStartFunction function() const { return function_; }
diff --git a/runtime/bin/thread_fuchsia.cc b/runtime/bin/thread_fuchsia.cc
index 57f4cd0..fa5397f 100644
--- a/runtime/bin/thread_fuchsia.cc
+++ b/runtime/bin/thread_fuchsia.cc
@@ -8,9 +8,9 @@
#include "bin/thread.h"
#include "bin/thread_fuchsia.h"
-#include <errno.h> // NOLINT
+#include <errno.h> // NOLINT
#include <sys/resource.h> // NOLINT
-#include <sys/time.h> // NOLINT
+#include <sys/time.h> // NOLINT
#include "platform/assert.h"
#include "platform/utils.h"
@@ -18,29 +18,28 @@
namespace dart {
namespace bin {
-#define VALIDATE_PTHREAD_RESULT(result) \
- if (result != 0) { \
- const int kBufferSize = 1024; \
- char error_buf[kBufferSize]; \
- FATAL2("pthread error: %d (%s)", result, \
- Utils::StrError(result, error_buf, kBufferSize)); \
+#define VALIDATE_PTHREAD_RESULT(result) \
+ if (result != 0) { \
+ const int kBufferSize = 1024; \
+ char error_buf[kBufferSize]; \
+ FATAL2("pthread error: %d (%s)", result, \
+ Utils::StrError(result, error_buf, kBufferSize)); \
}
#ifdef DEBUG
-#define RETURN_ON_PTHREAD_FAILURE(result) \
- if (result != 0) { \
- const int kBufferSize = 1024; \
- char error_buf[kBufferSize]; \
- fprintf(stderr, "%s:%d: pthread error: %d (%s)\n", \
- __FILE__, __LINE__, result, \
- Utils::StrError(result, error_buf, kBufferSize)); \
- return result; \
+#define RETURN_ON_PTHREAD_FAILURE(result) \
+ if (result != 0) { \
+ const int kBufferSize = 1024; \
+ char error_buf[kBufferSize]; \
+ fprintf(stderr, "%s:%d: pthread error: %d (%s)\n", __FILE__, __LINE__, \
+ result, Utils::StrError(result, error_buf, kBufferSize)); \
+ return result; \
}
#else
-#define RETURN_ON_PTHREAD_FAILURE(result) \
- if (result != 0) { \
- return result; \
+#define RETURN_ON_PTHREAD_FAILURE(result) \
+ if (result != 0) { \
+ return result; \
}
#endif
@@ -62,8 +61,7 @@
class ThreadStartData {
public:
- ThreadStartData(Thread::ThreadStartFunction function,
- uword parameter)
+ ThreadStartData(Thread::ThreadStartFunction function, uword parameter)
: function_(function), parameter_(parameter) {}
Thread::ThreadStartFunction function() const { return function_; }
diff --git a/runtime/bin/thread_linux.cc b/runtime/bin/thread_linux.cc
index 6ea923e..6e6971f 100644
--- a/runtime/bin/thread_linux.cc
+++ b/runtime/bin/thread_linux.cc
@@ -8,9 +8,9 @@
#include "bin/thread.h"
#include "bin/thread_linux.h"
-#include <errno.h> // NOLINT
+#include <errno.h> // NOLINT
#include <sys/resource.h> // NOLINT
-#include <sys/time.h> // NOLINT
+#include <sys/time.h> // NOLINT
#include "platform/assert.h"
#include "platform/utils.h"
@@ -18,29 +18,28 @@
namespace dart {
namespace bin {
-#define VALIDATE_PTHREAD_RESULT(result) \
- if (result != 0) { \
- const int kBufferSize = 1024; \
- char error_buf[kBufferSize]; \
- FATAL2("pthread error: %d (%s)", result, \
- Utils::StrError(result, error_buf, kBufferSize)); \
+#define VALIDATE_PTHREAD_RESULT(result) \
+ if (result != 0) { \
+ const int kBufferSize = 1024; \
+ char error_buf[kBufferSize]; \
+ FATAL2("pthread error: %d (%s)", result, \
+ Utils::StrError(result, error_buf, kBufferSize)); \
}
#ifdef DEBUG
-#define RETURN_ON_PTHREAD_FAILURE(result) \
- if (result != 0) { \
- const int kBufferSize = 1024; \
- char error_buf[kBufferSize]; \
- fprintf(stderr, "%s:%d: pthread error: %d (%s)\n", \
- __FILE__, __LINE__, result, \
- Utils::StrError(result, error_buf, kBufferSize)); \
- return result; \
+#define RETURN_ON_PTHREAD_FAILURE(result) \
+ if (result != 0) { \
+ const int kBufferSize = 1024; \
+ char error_buf[kBufferSize]; \
+ fprintf(stderr, "%s:%d: pthread error: %d (%s)\n", __FILE__, __LINE__, \
+ result, Utils::StrError(result, error_buf, kBufferSize)); \
+ return result; \
}
#else
-#define RETURN_ON_PTHREAD_FAILURE(result) \
- if (result != 0) { \
- return result; \
+#define RETURN_ON_PTHREAD_FAILURE(result) \
+ if (result != 0) { \
+ return result; \
}
#endif
@@ -62,8 +61,7 @@
class ThreadStartData {
public:
- ThreadStartData(Thread::ThreadStartFunction function,
- uword parameter)
+ ThreadStartData(Thread::ThreadStartFunction function, uword parameter)
: function_(function), parameter_(parameter) {}
Thread::ThreadStartFunction function() const { return function_; }
diff --git a/runtime/bin/thread_macos.cc b/runtime/bin/thread_macos.cc
index 9477e8ab..b63b0b9 100644
--- a/runtime/bin/thread_macos.cc
+++ b/runtime/bin/thread_macos.cc
@@ -8,16 +8,16 @@
#include "bin/thread.h"
#include "bin/thread_macos.h"
-#include <mach/mach_host.h> // NOLINT
-#include <mach/mach_init.h> // NOLINT
-#include <mach/mach_port.h> // NOLINT
-#include <mach/mach_traps.h> // NOLINT
-#include <mach/task_info.h> // NOLINT
-#include <mach/thread_act.h> // NOLINT
+#include <mach/mach_host.h> // NOLINT
+#include <mach/mach_init.h> // NOLINT
+#include <mach/mach_port.h> // NOLINT
+#include <mach/mach_traps.h> // NOLINT
+#include <mach/task_info.h> // NOLINT
+#include <mach/thread_act.h> // NOLINT
#include <mach/thread_info.h> // NOLINT
-#include <sys/errno.h> // NOLINT
-#include <sys/sysctl.h> // NOLINT
-#include <sys/types.h> // NOLINT
+#include <sys/errno.h> // NOLINT
+#include <sys/sysctl.h> // NOLINT
+#include <sys/types.h> // NOLINT
#include "platform/assert.h"
#include "platform/utils.h"
@@ -25,37 +25,36 @@
namespace dart {
namespace bin {
-#define VALIDATE_PTHREAD_RESULT(result) \
- if (result != 0) { \
- const int kBufferSize = 1024; \
- char error_message[kBufferSize]; \
- Utils::StrError(result, error_message, kBufferSize); \
- FATAL2("pthread error: %d (%s)", result, error_message); \
+#define VALIDATE_PTHREAD_RESULT(result) \
+ if (result != 0) { \
+ const int kBufferSize = 1024; \
+ char error_message[kBufferSize]; \
+ Utils::StrError(result, error_message, kBufferSize); \
+ FATAL2("pthread error: %d (%s)", result, error_message); \
}
#ifdef DEBUG
-#define RETURN_ON_PTHREAD_FAILURE(result) \
- if (result != 0) { \
- const int kBufferSize = 1024; \
- char error_message[kBufferSize]; \
- Utils::StrError(result, error_message, kBufferSize); \
- fprintf(stderr, "%s:%d: pthread error: %d (%s)\n", \
- __FILE__, __LINE__, result, error_message); \
- return result; \
+#define RETURN_ON_PTHREAD_FAILURE(result) \
+ if (result != 0) { \
+ const int kBufferSize = 1024; \
+ char error_message[kBufferSize]; \
+ Utils::StrError(result, error_message, kBufferSize); \
+ fprintf(stderr, "%s:%d: pthread error: %d (%s)\n", __FILE__, __LINE__, \
+ result, error_message); \
+ return result; \
}
#else
-#define RETURN_ON_PTHREAD_FAILURE(result) \
- if (result != 0) { \
- return result; \
+#define RETURN_ON_PTHREAD_FAILURE(result) \
+ if (result != 0) { \
+ return result; \
}
#endif
class ThreadStartData {
public:
- ThreadStartData(Thread::ThreadStartFunction function,
- uword parameter)
+ ThreadStartData(Thread::ThreadStartFunction function, uword parameter)
: function_(function), parameter_(parameter) {}
Thread::ThreadStartFunction function() const { return function_; }
@@ -311,9 +310,8 @@
(micros - (secs * kMicrosecondsPerSecond)) * kNanosecondsPerMicrosecond;
ts.tv_sec = static_cast<int32_t>(secs);
ts.tv_nsec = static_cast<long>(nanos); // NOLINT (long used in timespec).
- int result = pthread_cond_timedwait_relative_np(data_.cond(),
- data_.mutex(),
- &ts);
+ int result =
+ pthread_cond_timedwait_relative_np(data_.cond(), data_.mutex(), &ts);
ASSERT((result == 0) || (result == ETIMEDOUT));
if (result == ETIMEDOUT) {
retval = kTimedOut;
diff --git a/runtime/bin/thread_win.cc b/runtime/bin/thread_win.cc
index 92a9801..b491a51 100644
--- a/runtime/bin/thread_win.cc
+++ b/runtime/bin/thread_win.cc
@@ -133,11 +133,8 @@
TimeStamp kernel;
TimeStamp user;
HANDLE handle = OpenThread(THREAD_QUERY_INFORMATION, false, thread_id);
- BOOL result = GetThreadTimes(handle,
- &created.ft_,
- &exited.ft_,
- &kernel.ft_,
- &user.ft_);
+ BOOL result =
+ GetThreadTimes(handle, &created.ft_, &exited.ft_, &kernel.ft_, &user.ft_);
CloseHandle(handle);
if (!result) {
FATAL1("GetThreadCpuUsage failed %d\n", GetLastError());
@@ -234,10 +231,9 @@
void MonitorWaitData::ThreadExit() {
- if (MonitorWaitData::monitor_wait_data_key_ !=
- Thread::kUnsetThreadLocalKey) {
+ if (MonitorWaitData::monitor_wait_data_key_ != Thread::kUnsetThreadLocalKey) {
uword raw_wait_data =
- Thread::GetThreadLocal(MonitorWaitData::monitor_wait_data_key_);
+ Thread::GetThreadLocal(MonitorWaitData::monitor_wait_data_key_);
if (raw_wait_data != 0) {
MonitorWaitData* wait_data =
reinterpret_cast<MonitorWaitData*>(raw_wait_data);
@@ -351,7 +347,7 @@
// Get the MonitorWaitData object containing the event for this
// thread from thread local storage. Create it if it does not exist.
uword raw_wait_data =
- Thread::GetThreadLocal(MonitorWaitData::monitor_wait_data_key_);
+ Thread::GetThreadLocal(MonitorWaitData::monitor_wait_data_key_);
MonitorWaitData* wait_data = NULL;
if (raw_wait_data == 0) {
HANDLE event = CreateEvent(NULL, FALSE, FALSE, NULL);
diff --git a/runtime/bin/utils.h b/runtime/bin/utils.h
index 18b1db2..03c1578 100644
--- a/runtime/bin/utils.h
+++ b/runtime/bin/utils.h
@@ -16,12 +16,7 @@
class OSError {
public:
- enum SubSystem {
- kSystem,
- kGetAddressInfo,
- kBoringSSL,
- kUnknown = -1
- };
+ enum SubSystem { kSystem, kGetAddressInfo, kBoringSSL, kUnknown = -1 };
OSError();
OSError(int code, const char* message, SubSystem sub_system) {
diff --git a/runtime/bin/utils_android.cc b/runtime/bin/utils_android.cc
index 8c6ad24..e40d66a 100644
--- a/runtime/bin/utils_android.cc
+++ b/runtime/bin/utils_android.cc
@@ -5,10 +5,10 @@
#include "platform/globals.h"
#if defined(TARGET_OS_ANDROID)
-#include <errno.h> // NOLINT
-#include <netdb.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <netdb.h> // NOLINT
#include <sys/time.h> // NOLINT
-#include <time.h> // NOLINT
+#include <time.h> // NOLINT
#include "bin/utils.h"
#include "platform/assert.h"
@@ -43,29 +43,33 @@
}
-const char* StringUtils::ConsoleStringToUtf8(
- const char* str, intptr_t len, intptr_t* result_len) {
+const char* StringUtils::ConsoleStringToUtf8(const char* str,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
-const char* StringUtils::Utf8ToConsoleString(
- const char* utf8, intptr_t len, intptr_t* result_len) {
+const char* StringUtils::Utf8ToConsoleString(const char* utf8,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
-char* StringUtils::ConsoleStringToUtf8(
- char* str, intptr_t len, intptr_t* result_len) {
+char* StringUtils::ConsoleStringToUtf8(char* str,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
-char* StringUtils::Utf8ToConsoleString(
- char* utf8, intptr_t len, intptr_t* result_len) {
+char* StringUtils::Utf8ToConsoleString(char* utf8,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
@@ -81,8 +85,7 @@
}
-void TimerUtils::InitOnce() {
-}
+void TimerUtils::InitOnce() {}
int64_t TimerUtils::GetCurrentMonotonicMillis() {
diff --git a/runtime/bin/utils_fuchsia.cc b/runtime/bin/utils_fuchsia.cc
index 79a1fba..2425e49 100644
--- a/runtime/bin/utils_fuchsia.cc
+++ b/runtime/bin/utils_fuchsia.cc
@@ -40,29 +40,33 @@
}
-const char* StringUtils::ConsoleStringToUtf8(
- const char* str, intptr_t len, intptr_t* result_len) {
+const char* StringUtils::ConsoleStringToUtf8(const char* str,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
-const char* StringUtils::Utf8ToConsoleString(
- const char* utf8, intptr_t len, intptr_t* result_len) {
+const char* StringUtils::Utf8ToConsoleString(const char* utf8,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
-char* StringUtils::ConsoleStringToUtf8(
- char* str, intptr_t len, intptr_t* result_len) {
+char* StringUtils::ConsoleStringToUtf8(char* str,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
-char* StringUtils::Utf8ToConsoleString(
- char* utf8, intptr_t len, intptr_t* result_len) {
+char* StringUtils::Utf8ToConsoleString(char* utf8,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
@@ -78,8 +82,7 @@
}
-void TimerUtils::InitOnce() {
-}
+void TimerUtils::InitOnce() {}
int64_t TimerUtils::GetCurrentMonotonicMillis() {
@@ -94,8 +97,8 @@
void TimerUtils::Sleep(int64_t millis) {
- mx_nanosleep(
- millis * kMicrosecondsPerMillisecond * kNanosecondsPerMicrosecond);
+ mx_nanosleep(millis * kMicrosecondsPerMillisecond *
+ kNanosecondsPerMicrosecond);
}
} // namespace bin
diff --git a/runtime/bin/utils_linux.cc b/runtime/bin/utils_linux.cc
index 8266102..c59531f 100644
--- a/runtime/bin/utils_linux.cc
+++ b/runtime/bin/utils_linux.cc
@@ -5,10 +5,10 @@
#include "platform/globals.h"
#if defined(TARGET_OS_LINUX)
-#include <errno.h> // NOLINT
-#include <netdb.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <netdb.h> // NOLINT
#include <sys/time.h> // NOLINT
-#include <time.h> // NOLINT
+#include <time.h> // NOLINT
#include "bin/utils.h"
#include "platform/assert.h"
@@ -41,29 +41,33 @@
}
-const char* StringUtils::ConsoleStringToUtf8(
- const char* str, intptr_t len, intptr_t* result_len) {
+const char* StringUtils::ConsoleStringToUtf8(const char* str,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
-const char* StringUtils::Utf8ToConsoleString(
- const char* utf8, intptr_t len, intptr_t* result_len) {
+const char* StringUtils::Utf8ToConsoleString(const char* utf8,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
-char* StringUtils::ConsoleStringToUtf8(
- char* str, intptr_t len, intptr_t* result_len) {
+char* StringUtils::ConsoleStringToUtf8(char* str,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
-char* StringUtils::Utf8ToConsoleString(
- char* utf8, intptr_t len, intptr_t* result_len) {
+char* StringUtils::Utf8ToConsoleString(char* utf8,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
@@ -79,8 +83,7 @@
}
-void TimerUtils::InitOnce() {
-}
+void TimerUtils::InitOnce() {}
int64_t TimerUtils::GetCurrentMonotonicMillis() {
diff --git a/runtime/bin/utils_macos.cc b/runtime/bin/utils_macos.cc
index 97717c7..5753cd0 100644
--- a/runtime/bin/utils_macos.cc
+++ b/runtime/bin/utils_macos.cc
@@ -5,16 +5,16 @@
#include "platform/globals.h"
#if defined(TARGET_OS_MACOS)
-#include <errno.h> // NOLINT
-#include <mach/clock.h> // NOLINT
-#include <mach/mach.h> // NOLINT
+#include <errno.h> // NOLINT
+#include <mach/clock.h> // NOLINT
+#include <mach/mach.h> // NOLINT
#include <mach/mach_time.h> // NOLINT
-#include <netdb.h> // NOLINT
+#include <netdb.h> // NOLINT
#if TARGET_OS_IOS
#include <sys/sysctl.h> // NOLINT
#endif
#include <sys/time.h> // NOLINT
-#include <time.h> // NOLINT
+#include <time.h> // NOLINT
#include "bin/utils.h"
#include "platform/assert.h"
@@ -49,38 +49,42 @@
}
-const char* StringUtils::ConsoleStringToUtf8(
- const char* str, intptr_t len, intptr_t* result_len) {
+const char* StringUtils::ConsoleStringToUtf8(const char* str,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
-const char* StringUtils::Utf8ToConsoleString(
- const char* utf8, intptr_t len, intptr_t* result_len) {
+const char* StringUtils::Utf8ToConsoleString(const char* utf8,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
-char* StringUtils::ConsoleStringToUtf8(
- char* str, intptr_t len, intptr_t* result_len) {
+char* StringUtils::ConsoleStringToUtf8(char* str,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
-char* StringUtils::Utf8ToConsoleString(
- char* utf8, intptr_t len, intptr_t* result_len) {
+char* StringUtils::Utf8ToConsoleString(char* utf8,
+ intptr_t len,
+ intptr_t* result_len) {
UNIMPLEMENTED();
return NULL;
}
char* StringUtils::StrNDup(const char* s, intptr_t n) {
- // strndup has only been added to Mac OS X in 10.7. We are supplying
- // our own copy here if needed.
-#if !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || \
+// strndup has only been added to Mac OS X in 10.7. We are supplying
+// our own copy here if needed.
+#if !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || \
__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ <= 1060
intptr_t len = strlen(s);
if ((n < 0) || (len < 0)) {
@@ -95,7 +99,7 @@
}
result[len] = '\0';
return reinterpret_cast<char*>(memmove(result, s, len));
-#else // !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || ...
+#else // !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || ...
return strndup(s, n);
#endif // !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || ...
}
diff --git a/runtime/bin/utils_win.cc b/runtime/bin/utils_win.cc
index 4b0b1fa..8faa7d0 100644
--- a/runtime/bin/utils_win.cc
+++ b/runtime/bin/utils_win.cc
@@ -6,7 +6,7 @@
#if defined(TARGET_OS_WINDOWS)
#include <errno.h> // NOLINT
-#include <time.h> // NOLINT
+#include <time.h> // NOLINT
#include "bin/log.h"
#include "bin/utils.h"
@@ -17,18 +17,12 @@
namespace bin {
void FormatMessageIntoBuffer(DWORD code, wchar_t* buffer, int buffer_length) {
- DWORD message_size =
- FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL,
- code,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- buffer,
- buffer_length,
- NULL);
+ DWORD message_size = FormatMessageW(
+ FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, code,
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, buffer_length, NULL);
if (message_size == 0) {
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
- Log::PrintErr("FormatMessage failed for error code %d (error %d)\n",
- code,
+ Log::PrintErr("FormatMessage failed for error code %d (error %d)\n", code,
GetLastError());
}
_snwprintf(buffer, buffer_length, L"OS Error %d", code);
@@ -79,8 +73,8 @@
intptr_t* result_len) {
intptr_t wide_len;
wchar_t* wide = StringUtilsWin::Utf8ToWide(utf8, len, &wide_len);
- int system_len = WideCharToMultiByte(
- CP_ACP, 0, wide, wide_len, NULL, 0, NULL, NULL);
+ int system_len =
+ WideCharToMultiByte(CP_ACP, 0, wide, wide_len, NULL, 0, NULL, NULL);
char* ansi;
ansi =
reinterpret_cast<char*>(Dart_ScopeAllocate(system_len * sizeof(*ansi)));
@@ -100,8 +94,8 @@
intptr_t* result_len) {
// If len is -1 then WideCharToMultiByte will include the terminating
// NUL byte in the length.
- int utf8_len = WideCharToMultiByte(
- CP_UTF8, 0, wide, len, NULL, 0, NULL, NULL);
+ int utf8_len =
+ WideCharToMultiByte(CP_UTF8, 0, wide, len, NULL, 0, NULL, NULL);
char* utf8;
utf8 = reinterpret_cast<char*>(Dart_ScopeAllocate(utf8_len * sizeof(*utf8)));
WideCharToMultiByte(CP_UTF8, 0, wide, len, utf8, utf8_len, NULL, NULL);
@@ -129,31 +123,33 @@
}
-const char* StringUtils::Utf8ToConsoleString(
- const char* utf8, intptr_t len, intptr_t* result_len) {
- return const_cast<const char*>(
- StringUtils::Utf8ToConsoleString(
- const_cast<char*>(utf8), len, result_len));
+const char* StringUtils::Utf8ToConsoleString(const char* utf8,
+ intptr_t len,
+ intptr_t* result_len) {
+ return const_cast<const char*>(StringUtils::Utf8ToConsoleString(
+ const_cast<char*>(utf8), len, result_len));
}
-const char* StringUtils::ConsoleStringToUtf8(
- const char* str, intptr_t len, intptr_t* result_len) {
- return const_cast<const char*>(
- StringUtils::ConsoleStringToUtf8(
- const_cast<char*>(str), len, result_len));
+const char* StringUtils::ConsoleStringToUtf8(const char* str,
+ intptr_t len,
+ intptr_t* result_len) {
+ return const_cast<const char*>(StringUtils::ConsoleStringToUtf8(
+ const_cast<char*>(str), len, result_len));
}
-const char* StringUtilsWin::WideToUtf8(
- const wchar_t* wide, intptr_t len, intptr_t* result_len) {
+const char* StringUtilsWin::WideToUtf8(const wchar_t* wide,
+ intptr_t len,
+ intptr_t* result_len) {
return const_cast<const char*>(
StringUtilsWin::WideToUtf8(const_cast<wchar_t*>(wide), len, result_len));
}
-const wchar_t* StringUtilsWin::Utf8ToWide(
- const char* utf8, intptr_t len, intptr_t* result_len) {
+const wchar_t* StringUtilsWin::Utf8ToWide(const char* utf8,
+ intptr_t len,
+ intptr_t* result_len) {
return const_cast<const wchar_t*>(
StringUtilsWin::Utf8ToWide(const_cast<char*>(utf8), len, result_len));
}
@@ -190,8 +186,7 @@
}
for (int i = 0; i < unicode_argc; i++) {
wchar_t* arg = unicode_argv[i];
- int arg_len =
- WideCharToMultiByte(CP_UTF8, 0, arg, -1, NULL, 0, NULL, NULL);
+ int arg_len = WideCharToMultiByte(CP_UTF8, 0, arg, -1, NULL, 0, NULL, NULL);
char* utf8_arg = reinterpret_cast<char*>(malloc(arg_len));
WideCharToMultiByte(CP_UTF8, 0, arg, -1, utf8_arg, arg_len, NULL, NULL);
argv[i] = utf8_arg;
diff --git a/runtime/bin/utils_win.h b/runtime/bin/utils_win.h
index 2f63faf..a46bbb8 100644
--- a/runtime/bin/utils_win.h
+++ b/runtime/bin/utils_win.h
@@ -43,8 +43,8 @@
class WideToUtf8Scope {
public:
explicit WideToUtf8Scope(const wchar_t* wide) {
- intptr_t utf8_len = WideCharToMultiByte(
- CP_UTF8, 0, wide, -1, NULL, 0, NULL, NULL);
+ intptr_t utf8_len =
+ WideCharToMultiByte(CP_UTF8, 0, wide, -1, NULL, 0, NULL, NULL);
char* utf8 = new char[utf8_len];
WideCharToMultiByte(CP_UTF8, 0, wide, -1, utf8, utf8_len, NULL, NULL);
length_ = utf8_len;
@@ -77,9 +77,7 @@
wide_ = wide;
}
- ~Utf8ToWideScope() {
- delete[] wide_;
- }
+ ~Utf8ToWideScope() { delete[] wide_; }
wchar_t* wide() const { return wide_; }
intptr_t length() const { return length_; }
diff --git a/runtime/bin/vmservice_dartium.cc b/runtime/bin/vmservice_dartium.cc
index e523dad..613b005 100644
--- a/runtime/bin/vmservice_dartium.cc
+++ b/runtime/bin/vmservice_dartium.cc
@@ -22,8 +22,7 @@
Dart_ExitScope(); \
Dart_ShutdownIsolate(); \
return 0; \
- } \
-
+ }
static const char* DEFAULT_VM_SERVICE_SERVER_IP = "127.0.0.1";
@@ -43,16 +42,12 @@
Dart_Isolate VmServiceServer::CreateIsolate(const uint8_t* snapshot_buffer) {
ASSERT(snapshot_buffer != NULL);
// Create the isolate.
- IsolateData* isolate_data = new IsolateData(DART_VM_SERVICE_ISOLATE_NAME,
- NULL,
- NULL);
+ IsolateData* isolate_data =
+ new IsolateData(DART_VM_SERVICE_ISOLATE_NAME, NULL, NULL);
char* error = 0;
- Dart_Isolate isolate = Dart_CreateIsolate(DART_VM_SERVICE_ISOLATE_NAME,
- "main",
- snapshot_buffer,
- NULL,
- isolate_data,
- &error);
+ Dart_Isolate isolate =
+ Dart_CreateIsolate(DART_VM_SERVICE_ISOLATE_NAME, "main", snapshot_buffer,
+ NULL, isolate_data, &error);
if (!isolate) {
fprintf(stderr, "Dart_CreateIsolate failed: %s\n", error);
return 0;
@@ -63,12 +58,11 @@
Builtin::SetNativeResolver(Builtin::kIOLibrary);
ASSERT(Dart_IsServiceIsolate(isolate));
- if (!VmService::Setup(DEFAULT_VM_SERVICE_SERVER_IP,
- DEFAULT_VM_SERVICE_SERVER_PORT,
- false /* running_precompiled */,
- false /* disable origin checks */)) {
- fprintf(stderr,
- "Vmservice::Setup failed: %s\n", VmService::GetErrorMessage());
+ if (!VmService::Setup(
+ DEFAULT_VM_SERVICE_SERVER_IP, DEFAULT_VM_SERVICE_SERVER_PORT,
+ false /* running_precompiled */, false /* disable origin checks */)) {
+ fprintf(stderr, "Vmservice::Setup failed: %s\n",
+ VmService::GetErrorMessage());
isolate = NULL;
}
Dart_ExitScope();
@@ -146,7 +140,7 @@
/* DISALLOW_ALLOCATION */
-void VmServiceServer::operator delete(void* pointer) {
+void VmServiceServer::operator delete(void* pointer) {
fprintf(stderr, "unreachable code\n");
abort();
}
diff --git a/runtime/bin/vmservice_dartium.h b/runtime/bin/vmservice_dartium.h
index dfbf768..472df34 100644
--- a/runtime/bin/vmservice_dartium.h
+++ b/runtime/bin/vmservice_dartium.h
@@ -20,15 +20,18 @@
static const char* GetServerAddress();
- static void DecompressAssets(const uint8_t* input, unsigned int input_len,
- uint8_t** output, unsigned int* output_length);
+ static void DecompressAssets(const uint8_t* input,
+ unsigned int input_len,
+ uint8_t** output,
+ unsigned int* output_length);
-/* DISALLOW_ALLOCATION */
+ /* DISALLOW_ALLOCATION */
void operator delete(void* pointer);
+
private:
void* operator new(size_t size);
-/* DISALLOW_IMPLICIT_CONSTRUCTORS */
+ /* DISALLOW_IMPLICIT_CONSTRUCTORS */
VmServiceServer();
VmServiceServer(const VmServiceServer&);
void operator=(const VmServiceServer&);
diff --git a/runtime/bin/vmservice_impl.cc b/runtime/bin/vmservice_impl.cc
index 004cf66..da2dd8d 100644
--- a/runtime/bin/vmservice_impl.cc
+++ b/runtime/bin/vmservice_impl.cc
@@ -17,17 +17,17 @@
namespace dart {
namespace bin {
-#define RETURN_ERROR_HANDLE(handle) \
- if (Dart_IsError(handle)) { \
- return handle; \
+#define RETURN_ERROR_HANDLE(handle) \
+ if (Dart_IsError(handle)) { \
+ return handle; \
}
-#define SHUTDOWN_ON_ERROR(handle) \
- if (Dart_IsError(handle)) { \
- error_msg_ = strdup(Dart_GetError(handle)); \
- Dart_ExitScope(); \
- Dart_ShutdownIsolate(); \
- return false; \
+#define SHUTDOWN_ON_ERROR(handle) \
+ if (Dart_IsError(handle)) { \
+ error_msg_ = strdup(Dart_GetError(handle)); \
+ Dart_ExitScope(); \
+ Dart_ShutdownIsolate(); \
+ return false; \
}
#define kLibrarySourceNamePrefix "/vmservice"
@@ -122,8 +122,8 @@
static VmServiceIONativeEntry _VmServiceIONativeEntries[] = {
- {"VMServiceIO_NotifyServerState", 1, NotifyServerState},
- {"VMServiceIO_Shutdown", 0, Shutdown },
+ {"VMServiceIO_NotifyServerState", 1, NotifyServerState},
+ {"VMServiceIO_Shutdown", 0, Shutdown},
};
@@ -230,15 +230,13 @@
}
result = DartUtils::SetIntegerField(library, "_port", server_port);
SHUTDOWN_ON_ERROR(result);
- result = Dart_SetField(library,
- DartUtils::NewString("_autoStart"),
+ result = Dart_SetField(library, DartUtils::NewString("_autoStart"),
Dart_NewBoolean(auto_start));
SHUTDOWN_ON_ERROR(result);
- result = Dart_SetField(library,
- DartUtils::NewString("_originCheckDisabled"),
+ result = Dart_SetField(library, DartUtils::NewString("_originCheckDisabled"),
Dart_NewBoolean(dev_mode_server));
- // Are we running on Windows?
+// Are we running on Windows?
#if defined(TARGET_OS_WINDOWS)
Dart_Handle is_windows = Dart_True();
#else
@@ -248,7 +246,7 @@
Dart_SetField(library, DartUtils::NewString("_isWindows"), is_windows);
SHUTDOWN_ON_ERROR(result);
- // Are we running on Fuchsia?
+// Are we running on Fuchsia?
#if defined(TARGET_OS_FUCHSIA)
Dart_Handle is_fuchsia = Dart_True();
#else
@@ -270,8 +268,7 @@
SHUTDOWN_ON_ERROR(signal_watch);
Dart_Handle field_name = Dart_NewStringFromCString("_signalWatch");
SHUTDOWN_ON_ERROR(field_name);
- result =
- Dart_SetField(library, field_name, signal_watch);
+ result = Dart_SetField(library, field_name, signal_watch);
SHUTDOWN_ON_ERROR(field_name);
return true;
}
@@ -298,7 +295,8 @@
Dart_Handle VmService::GetSource(const char* name) {
const intptr_t kBufferSize = 512;
char buffer[kBufferSize];
- snprintf(&buffer[0], kBufferSize-1, "%s/%s", kLibrarySourceNamePrefix, name);
+ snprintf(&buffer[0], kBufferSize - 1, "%s/%s", kLibrarySourceNamePrefix,
+ name);
const char* vmservice_source = NULL;
int r = Resources::ResourceLookup(buffer, &vmservice_source);
if (r == Resources::kNoSuchInstance) {
diff --git a/runtime/bin/vmservice_impl.h b/runtime/bin/vmservice_impl.h
index f923dca..9f9ce6b 100644
--- a/runtime/bin/vmservice_impl.h
+++ b/runtime/bin/vmservice_impl.h
@@ -25,9 +25,7 @@
static const char* GetErrorMessage();
// HTTP Server's address.
- static const char* GetServerAddress() {
- return &server_uri_[0];
- }
+ static const char* GetServerAddress() { return &server_uri_[0]; }
private:
static const intptr_t kServerUriStringBufferSize = 1024;
@@ -40,7 +38,8 @@
static Dart_Handle LoadSource(Dart_Handle library, const char* name);
static Dart_Handle LoadResources(Dart_Handle library);
static Dart_Handle LoadResource(Dart_Handle library, const char* name);
- static Dart_Handle LibraryTagHandler(Dart_LibraryTag tag, Dart_Handle library,
+ static Dart_Handle LibraryTagHandler(Dart_LibraryTag tag,
+ Dart_Handle library,
Dart_Handle url);
static const char* error_msg_;
diff --git a/runtime/include/dart_api.h b/runtime/include/dart_api.h
index 2608724..bc60b3b 100755
--- a/runtime/include/dart_api.h
+++ b/runtime/include/dart_api.h
@@ -2940,6 +2940,19 @@
Dart_Handle import,
Dart_Handle prefix);
+
+/**
+ * Returns a flattened list of pairs. The first element in each pair is the
+ * importing library and and the second element is the imported library for each
+ * import in the isolate of a library whose URI's scheme is [scheme].
+ *
+ * Requires there to be a current isolate.
+ *
+ * \return A handle to a list of flattened pairs of importer-importee.
+ */
+DART_EXPORT Dart_Handle Dart_GetImportsOfScheme(Dart_Handle scheme);
+
+
/**
* Called by the embedder to provide the source for a "part of"
* directive. This function should be called in response to a
diff --git a/runtime/lib/array.cc b/runtime/lib/array.cc
index b95e6b0..9d43816 100644
--- a/runtime/lib/array.cc
+++ b/runtime/lib/array.cc
@@ -54,20 +54,14 @@
GET_NON_NULL_NATIVE_ARGUMENT(Bool, needs_type_arg, arguments->NativeArgAt(3));
intptr_t istart = start.Value();
if ((istart < 0) || (istart > src.Length())) {
- Exceptions::ThrowRangeError(
- "start",
- start,
- 0,
- src.Length());
+ Exceptions::ThrowRangeError("start", start, 0, src.Length());
}
intptr_t icount = count.Value();
// Zero count should be handled outside already.
if ((icount <= 0) || (icount > src.Length())) {
- Exceptions::ThrowRangeError(
- "count",
- count,
- 0, // This is the limit the user sees.
- src.Length() - istart);
+ Exceptions::ThrowRangeError("count", count,
+ 0, // This is the limit the user sees.
+ src.Length() - istart);
}
return src.Slice(istart, icount, needs_type_arg.value());
diff --git a/runtime/lib/date.cc b/runtime/lib/date.cc
index ba9fa95..137652b 100644
--- a/runtime/lib/date.cc
+++ b/runtime/lib/date.cc
@@ -15,8 +15,8 @@
static int64_t kMaxAllowedSeconds = kMaxInt32;
DEFINE_NATIVE_ENTRY(DateTime_timeZoneName, 1) {
- GET_NON_NULL_NATIVE_ARGUMENT(
- Integer, dart_seconds, arguments->NativeArgAt(0));
+ GET_NON_NULL_NATIVE_ARGUMENT(Integer, dart_seconds,
+ arguments->NativeArgAt(0));
int64_t seconds = dart_seconds.AsInt64Value();
if (llabs(seconds) > kMaxAllowedSeconds) {
Exceptions::ThrowArgumentError(dart_seconds);
@@ -27,8 +27,8 @@
DEFINE_NATIVE_ENTRY(DateTime_timeZoneOffsetInSeconds, 1) {
- GET_NON_NULL_NATIVE_ARGUMENT(
- Integer, dart_seconds, arguments->NativeArgAt(0));
+ GET_NON_NULL_NATIVE_ARGUMENT(Integer, dart_seconds,
+ arguments->NativeArgAt(0));
int64_t seconds = dart_seconds.AsInt64Value();
if (llabs(seconds) > kMaxAllowedSeconds) {
Exceptions::ThrowArgumentError(dart_seconds);
diff --git a/runtime/lib/developer.cc b/runtime/lib/developer.cc
index a0e315f..5d6027b 100644
--- a/runtime/lib/developer.cc
+++ b/runtime/lib/developer.cc
@@ -59,15 +59,9 @@
GET_NATIVE_ARGUMENT(Instance, dart_zone, arguments->NativeArgAt(5));
GET_NATIVE_ARGUMENT(Instance, error, arguments->NativeArgAt(6));
GET_NATIVE_ARGUMENT(Instance, stack_trace, arguments->NativeArgAt(7));
- Service::SendLogEvent(isolate,
- sequence.AsInt64Value(),
- timestamp.AsInt64Value(),
- level.Value(),
- name,
- message,
- dart_zone,
- error,
- stack_trace);
+ Service::SendLogEvent(isolate, sequence.AsInt64Value(),
+ timestamp.AsInt64Value(), level.Value(), name, message,
+ dart_zone, error, stack_trace);
return Object::null();
#endif // PRODUCT
}
@@ -141,8 +135,8 @@
static void SendNull(const SendPort& port) {
const Dart_Port destination_port_id = port.Id();
- PortMap::PostMessage(new Message(
- destination_port_id, Object::null(), Message::kNormalPriority));
+ PortMap::PostMessage(new Message(destination_port_id, Object::null(),
+ Message::kNormalPriority));
}
diff --git a/runtime/lib/double.cc b/runtime/lib/double.cc
index c28e1b1..2cd1921 100644
--- a/runtime/lib/double.cc
+++ b/runtime/lib/double.cc
@@ -144,8 +144,8 @@
GET_NON_NULL_NATIVE_ARGUMENT(Double, right, arguments->NativeArgAt(1));
bool result = right.IsNull() ? false : (left.value() > right.value());
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Double_greaterThan %s > %s\n",
- left.ToCString(), right.ToCString());
+ OS::Print("Double_greaterThan %s > %s\n", left.ToCString(),
+ right.ToCString());
}
return Bool::Get(result).raw();
}
@@ -163,8 +163,7 @@
GET_NON_NULL_NATIVE_ARGUMENT(Double, right, arguments->NativeArgAt(1));
bool result = right.IsNull() ? false : (left.value() == right.value());
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Double_equal %s == %s\n",
- left.ToCString(), right.ToCString());
+ OS::Print("Double_equal %s == %s\n", left.ToCString(), right.ToCString());
}
return Bool::Get(result).raw();
}
@@ -245,8 +244,8 @@
GET_NON_NULL_NATIVE_ARGUMENT(Smi, fraction_digits, arguments->NativeArgAt(1));
double d = arg.value();
intptr_t fraction_digits_value = fraction_digits.Value();
- if (0 <= fraction_digits_value && fraction_digits_value <= 20
- && kLowerBoundary < d && d < kUpperBoundary) {
+ if (0 <= fraction_digits_value && fraction_digits_value <= 20 &&
+ kLowerBoundary < d && d < kUpperBoundary) {
return DoubleToStringAsFixed(d, static_cast<int>(fraction_digits_value));
} else {
Exceptions::ThrowArgumentError(String::Handle(
@@ -262,8 +261,8 @@
double d = arg.value();
intptr_t fraction_digits_value = fraction_digits.Value();
if (-1 <= fraction_digits_value && fraction_digits_value <= 20) {
- return DoubleToStringAsExponential(
- d, static_cast<int>(fraction_digits_value));
+ return DoubleToStringAsExponential(d,
+ static_cast<int>(fraction_digits_value));
} else {
Exceptions::ThrowArgumentError(String::Handle(
String::New("Illegal arguments to double.toStringAsExponential")));
diff --git a/runtime/lib/errors.cc b/runtime/lib/errors.cc
index 75f354d..390079f 100644
--- a/runtime/lib/errors.cc
+++ b/runtime/lib/errors.cc
@@ -26,8 +26,8 @@
StackFrame* stack_frame = iterator->NextFrame();
Code& code = Code::Handle();
Function& func = Function::Handle();
- const Class& assert_error_class = Class::Handle(
- Library::LookupCoreClass(Symbols::AssertionError()));
+ const Class& assert_error_class =
+ Class::Handle(Library::LookupCoreClass(Symbols::AssertionError()));
ASSERT(!assert_error_class.IsNull());
bool hit_assertion_error = false;
while (stack_frame != NULL) {
@@ -84,8 +84,8 @@
script.GetTokenLocation(assertion_end, &to_line, &to_column);
// The snippet will extract the correct assertion code even if the source
// is generated.
- args.SetAt(0, String::Handle(
- script.GetSnippet(from_line, from_column, to_line, to_column)));
+ args.SetAt(0, String::Handle(script.GetSnippet(from_line, from_column,
+ to_line, to_column)));
// Initialize location arguments starting at position 1.
// Do not set a column if the source has been generated as it will be wrong.
@@ -118,8 +118,8 @@
const String& dst_name = String::CheckedHandle(arguments->NativeArgAt(3));
const String& error_msg = String::CheckedHandle(arguments->NativeArgAt(4));
const AbstractType& src_type = AbstractType::Handle(src_value.GetType());
- Exceptions::CreateAndThrowTypeError(
- location, src_type, dst_type, dst_name, error_msg);
+ Exceptions::CreateAndThrowTypeError(location, src_type, dst_type, dst_name,
+ error_msg);
UNREACHABLE();
return Object::null();
}
diff --git a/runtime/lib/function.cc b/runtime/lib/function.cc
index 4241762..2abdde71 100644
--- a/runtime/lib/function.cc
+++ b/runtime/lib/function.cc
@@ -16,9 +16,8 @@
DEFINE_NATIVE_ENTRY(Function_apply, 2) {
const Array& fun_arguments = Array::CheckedHandle(arguments->NativeArgAt(0));
const Array& fun_arg_names = Array::CheckedHandle(arguments->NativeArgAt(1));
- const Array& fun_args_desc =
- Array::Handle(ArgumentsDescriptor::New(fun_arguments.Length(),
- fun_arg_names));
+ const Array& fun_args_desc = Array::Handle(
+ ArgumentsDescriptor::New(fun_arguments.Length(), fun_arg_names));
const Object& result =
Object::Handle(DartEntry::InvokeClosure(fun_arguments, fun_args_desc));
if (result.IsError()) {
@@ -29,8 +28,8 @@
DEFINE_NATIVE_ENTRY(Closure_equals, 2) {
- const Closure& receiver = Closure::CheckedHandle(
- zone, arguments->NativeArgAt(0));
+ const Closure& receiver =
+ Closure::CheckedHandle(zone, arguments->NativeArgAt(0));
GET_NATIVE_ARGUMENT(Instance, other, arguments->NativeArgAt(1));
ASSERT(!other.IsNull());
if (receiver.raw() == other.raw()) return Bool::True().raw();
@@ -41,8 +40,8 @@
ASSERT(!func_a.IsImplicitStaticClosureFunction());
if (func_a.IsImplicitInstanceClosureFunction()) {
const Context& context_a = Context::Handle(receiver.context());
- const Context& context_b = Context::Handle(
- Closure::Cast(other).context());
+ const Context& context_b =
+ Context::Handle(Closure::Cast(other).context());
const Object& receiver_a = Object::Handle(context_a.At(0));
const Object& receiver_b = Object::Handle(context_b.At(0));
if (receiver_a.raw() == receiver_b.raw()) return Bool::True().raw();
@@ -51,8 +50,8 @@
func_b.IsImplicitInstanceClosureFunction()) {
// TODO(rmacnak): Patch existing tears off during reload instead.
const Context& context_a = Context::Handle(receiver.context());
- const Context& context_b = Context::Handle(
- Closure::Cast(other).context());
+ const Context& context_b =
+ Context::Handle(Closure::Cast(other).context());
const Object& receiver_a = Object::Handle(context_a.At(0));
const Object& receiver_b = Object::Handle(context_b.At(0));
if ((receiver_a.raw() == receiver_b.raw()) &&
@@ -67,8 +66,8 @@
DEFINE_NATIVE_ENTRY(Closure_hashCode, 1) {
- const Closure& receiver = Closure::CheckedHandle(
- zone, arguments->NativeArgAt(0));
+ const Closure& receiver =
+ Closure::CheckedHandle(zone, arguments->NativeArgAt(0));
const Function& func = Function::Handle(receiver.function());
// Hash together name, class name and signature.
const Class& cls = Class::Handle(func.Owner());
@@ -85,8 +84,8 @@
DEFINE_NATIVE_ENTRY(Closure_clone, 1) {
- const Closure& receiver = Closure::CheckedHandle(
- zone, arguments->NativeArgAt(0));
+ const Closure& receiver =
+ Closure::CheckedHandle(zone, arguments->NativeArgAt(0));
const Function& func = Function::Handle(zone, receiver.function());
const Context& ctx = Context::Handle(zone, receiver.context());
Context& cloned_ctx =
diff --git a/runtime/lib/growable_array.cc b/runtime/lib/growable_array.cc
index e892813..501cea6 100644
--- a/runtime/lib/growable_array.cc
+++ b/runtime/lib/growable_array.cc
@@ -17,11 +17,10 @@
TypeArguments::CheckedHandle(arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(Array, data, arguments->NativeArgAt(1));
if (data.Length() <= 0) {
- Exceptions::ThrowRangeError(
- "length",
- Integer::Handle(Integer::New(data.Length())),
- 0, // This is the limit the user sees.
- Array::kMaxElements);
+ Exceptions::ThrowRangeError("length",
+ Integer::Handle(Integer::New(data.Length())),
+ 0, // This is the limit the user sees.
+ Array::kMaxElements);
}
const GrowableObjectArray& new_array =
GrowableObjectArray::Handle(GrowableObjectArray::New(data));
diff --git a/runtime/lib/integers.cc b/runtime/lib/integers.cc
index efb12af..3624178 100644
--- a/runtime/lib/integers.cc
+++ b/runtime/lib/integers.cc
@@ -16,8 +16,10 @@
namespace dart {
-DEFINE_FLAG(bool, trace_intrinsified_natives, false,
- "Report if any of the intrinsified natives are called");
+DEFINE_FLAG(bool,
+ trace_intrinsified_natives,
+ false,
+ "Report if any of the intrinsified natives are called");
// Smi natives.
@@ -42,8 +44,8 @@
ASSERT(CheckInteger(right));
ASSERT(CheckInteger(left));
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Integer_bitAndFromInteger %s & %s\n",
- right.ToCString(), left.ToCString());
+ OS::Print("Integer_bitAndFromInteger %s & %s\n", right.ToCString(),
+ left.ToCString());
}
const Integer& result = Integer::Handle(left.BitOp(Token::kBIT_AND, right));
// A null result indicates that a bigint operation is required.
@@ -57,8 +59,8 @@
ASSERT(CheckInteger(right));
ASSERT(CheckInteger(left));
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Integer_bitOrFromInteger %s | %s\n",
- left.ToCString(), right.ToCString());
+ OS::Print("Integer_bitOrFromInteger %s | %s\n", left.ToCString(),
+ right.ToCString());
}
const Integer& result = Integer::Handle(left.BitOp(Token::kBIT_OR, right));
// A null result indicates that a bigint operation is required.
@@ -72,8 +74,8 @@
ASSERT(CheckInteger(right));
ASSERT(CheckInteger(left));
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Integer_bitXorFromInteger %s ^ %s\n",
- left.ToCString(), right.ToCString());
+ OS::Print("Integer_bitXorFromInteger %s ^ %s\n", left.ToCString(),
+ right.ToCString());
}
const Integer& result = Integer::Handle(left.BitOp(Token::kBIT_XOR, right));
// A null result indicates that a bigint operation is required.
@@ -87,8 +89,8 @@
ASSERT(CheckInteger(right_int));
ASSERT(CheckInteger(left_int));
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Integer_addFromInteger %s + %s\n",
- left_int.ToCString(), right_int.ToCString());
+ OS::Print("Integer_addFromInteger %s + %s\n", left_int.ToCString(),
+ right_int.ToCString());
}
const Integer& result =
Integer::Handle(left_int.ArithmeticOp(Token::kADD, right_int));
@@ -103,8 +105,8 @@
ASSERT(CheckInteger(right_int));
ASSERT(CheckInteger(left_int));
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Integer_subFromInteger %s - %s\n",
- left_int.ToCString(), right_int.ToCString());
+ OS::Print("Integer_subFromInteger %s - %s\n", left_int.ToCString(),
+ right_int.ToCString());
}
const Integer& result =
Integer::Handle(left_int.ArithmeticOp(Token::kSUB, right_int));
@@ -119,8 +121,8 @@
ASSERT(CheckInteger(right_int));
ASSERT(CheckInteger(left_int));
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Integer_mulFromInteger %s * %s\n",
- left_int.ToCString(), right_int.ToCString());
+ OS::Print("Integer_mulFromInteger %s * %s\n", left_int.ToCString(),
+ right_int.ToCString());
}
const Integer& result =
Integer::Handle(left_int.ArithmeticOp(Token::kMUL, right_int));
@@ -148,8 +150,8 @@
ASSERT(CheckInteger(right_int));
ASSERT(CheckInteger(left_int));
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Integer_moduloFromInteger %s mod %s\n",
- left_int.ToCString(), right_int.ToCString());
+ OS::Print("Integer_moduloFromInteger %s mod %s\n", left_int.ToCString(),
+ right_int.ToCString());
}
if (right_int.IsZero()) {
// Should have been caught before calling into runtime.
@@ -168,8 +170,8 @@
ASSERT(CheckInteger(right));
ASSERT(CheckInteger(left));
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Integer_greaterThanFromInteger %s > %s\n",
- left.ToCString(), right.ToCString());
+ OS::Print("Integer_greaterThanFromInteger %s > %s\n", left.ToCString(),
+ right.ToCString());
}
return Bool::Get(left.CompareWith(right) == 1).raw();
}
@@ -181,8 +183,8 @@
ASSERT(CheckInteger(left));
ASSERT(CheckInteger(right));
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Integer_equalToInteger %s == %s\n",
- left.ToCString(), right.ToCString());
+ OS::Print("Integer_equalToInteger %s == %s\n", left.ToCString(),
+ right.ToCString());
}
return Bool::Get(left.CompareWith(right) == 0).raw();
}
@@ -289,8 +291,8 @@
const Smi& left = Smi::CheckedHandle(arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(Smi, right, arguments->NativeArgAt(1));
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Smi_bitAndFromSmi %s & %s\n",
- left.ToCString(), right.ToCString());
+ OS::Print("Smi_bitAndFromSmi %s & %s\n", left.ToCString(),
+ right.ToCString());
}
const Smi& left_value = Smi::Cast(left);
const Smi& right_value = Smi::Cast(right);
@@ -303,25 +305,24 @@
GET_NON_NULL_NATIVE_ARGUMENT(Integer, value, arguments->NativeArgAt(1));
ASSERT(CheckInteger(amount));
ASSERT(CheckInteger(value));
- const Integer& result = Integer::Handle(
- ShiftOperationHelper(Token::kSHR, value, amount));
+ const Integer& result =
+ Integer::Handle(ShiftOperationHelper(Token::kSHR, value, amount));
// A null result indicates that a bigint operation is required.
return result.IsNull() ? result.raw() : result.AsValidInteger();
}
-
DEFINE_NATIVE_ENTRY(Smi_shlFromInt, 2) {
const Smi& amount = Smi::CheckedHandle(arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(Integer, value, arguments->NativeArgAt(1));
ASSERT(CheckInteger(amount));
ASSERT(CheckInteger(value));
if (FLAG_trace_intrinsified_natives) {
- OS::Print("Smi_shlFromInt: %s << %s\n",
- value.ToCString(), amount.ToCString());
+ OS::Print("Smi_shlFromInt: %s << %s\n", value.ToCString(),
+ amount.ToCString());
}
- const Integer& result = Integer::Handle(
- ShiftOperationHelper(Token::kSHL, value, amount));
+ const Integer& result =
+ Integer::Handle(ShiftOperationHelper(Token::kSHL, value, amount));
// A null result indicates that a bigint operation is required.
return result.IsNull() ? result.raw() : result.AsValidInteger();
}
diff --git a/runtime/lib/invocation_mirror.h b/runtime/lib/invocation_mirror.h
index b2b152e8..6061c84 100644
--- a/runtime/lib/invocation_mirror.h
+++ b/runtime/lib/invocation_mirror.h
@@ -20,7 +20,7 @@
kMethod = 0,
kGetter = 1,
kSetter = 2,
- kField = 3,
+ kField = 3,
kLocalVar = 4,
kTypeShift = 0,
kTypeBits = 3,
@@ -32,7 +32,7 @@
// NoSuchMethodError for compile-time resolution failures.
kDynamic = 0,
kSuper = 1,
- kStatic = 2,
+ kStatic = 2,
kConstructor = 3,
kTopLevel = 4,
kCallShift = kTypeBits,
diff --git a/runtime/lib/isolate.cc b/runtime/lib/isolate.cc
index 54a55ee..d88fbc8 100644
--- a/runtime/lib/isolate.cc
+++ b/runtime/lib/isolate.cc
@@ -25,7 +25,9 @@
namespace dart {
-DEFINE_FLAG(bool, i_like_slow_isolate_spawn, false,
+DEFINE_FLAG(bool,
+ i_like_slow_isolate_spawn,
+ false,
"Block the parent thread when loading spawned isolates.");
static uint8_t* allocator(uint8_t* ptr, intptr_t old_size, intptr_t new_size) {
@@ -60,8 +62,7 @@
DEFINE_NATIVE_ENTRY(RawReceivePortImpl_factory, 1) {
ASSERT(TypeArguments::CheckedHandle(arguments->NativeArgAt(0)).IsNull());
- Dart_Port port_id =
- PortMap::CreatePort(isolate->message_handler());
+ Dart_Port port_id = PortMap::CreatePort(isolate->message_handler());
return ReceivePort::New(port_id, false /* not control port */);
}
@@ -111,16 +112,16 @@
const bool can_send_any_object = isolate->origin_id() == port.origin_id();
if (ApiObjectConverter::CanConvert(obj.raw())) {
- PortMap::PostMessage(new Message(
- destination_port_id, obj.raw(), Message::kNormalPriority));
+ PortMap::PostMessage(
+ new Message(destination_port_id, obj.raw(), Message::kNormalPriority));
} else {
uint8_t* data = NULL;
MessageWriter writer(&data, &allocator, can_send_any_object);
writer.WriteMessage(obj);
// TODO(turnidge): Throw an exception when the return value is false?
- PortMap::PostMessage(new Message(destination_port_id,
- data, writer.BytesWritten(),
+ PortMap::PostMessage(new Message(destination_port_id, data,
+ writer.BytesWritten(),
Message::kNormalPriority));
}
return Object::null();
@@ -154,14 +155,9 @@
// Make a copy of the state's isolate flags and hand it to the callback.
Dart_IsolateFlags api_flags = *(state_->isolate_flags());
- Isolate* isolate = reinterpret_cast<Isolate*>(
- (callback)(state_->script_url(),
- state_->function_name(),
- state_->package_root(),
- state_->package_config(),
- &api_flags,
- state_->init_data(),
- &error));
+ Isolate* isolate = reinterpret_cast<Isolate*>((callback)(
+ state_->script_url(), state_->function_name(), state_->package_root(),
+ state_->package_config(), &api_flags, state_->init_data(), &error));
state_->DecrementSpawnCount();
if (isolate == NULL) {
ReportError(error);
@@ -245,21 +241,12 @@
Dart_Port on_exit_port = onExit.IsNull() ? ILLEGAL_PORT : onExit.Id();
Dart_Port on_error_port = onError.IsNull() ? ILLEGAL_PORT : onError.Id();
- IsolateSpawnState* state =
- new IsolateSpawnState(port.Id(),
- isolate->origin_id(),
- isolate->init_callback_data(),
- String2UTF8(script_uri),
- func,
- message,
- isolate->spawn_count_monitor(),
- isolate->spawn_count(),
- utf8_package_root,
- utf8_package_config,
- paused.value(),
- fatal_errors,
- on_exit_port,
- on_error_port);
+ IsolateSpawnState* state = new IsolateSpawnState(
+ port.Id(), isolate->origin_id(), isolate->init_callback_data(),
+ String2UTF8(script_uri), func, message,
+ isolate->spawn_count_monitor(), isolate->spawn_count(),
+ utf8_package_root, utf8_package_config, paused.value(), fatal_errors,
+ on_exit_port, on_error_port);
ThreadPool::Task* spawn_task = new SpawnIsolateTask(state);
isolate->IncrementSpawnCount();
@@ -300,9 +287,9 @@
if (handler != NULL) {
TransitionVMToNative transition(thread);
Dart_EnterScope();
- Dart_Handle handle = handler(Dart_kCanonicalizeUrl,
- Api::NewHandle(thread, library.raw()),
- Api::NewHandle(thread, uri.raw()));
+ Dart_Handle handle =
+ handler(Dart_kCanonicalizeUrl, Api::NewHandle(thread, library.raw()),
+ Api::NewHandle(thread, uri.raw()));
const Object& obj = Object::Handle(Api::UnwrapHandle(handle));
if (obj.IsString()) {
result = String2UTF8(String::Cast(obj));
@@ -312,9 +299,10 @@
*error = zone->PrintToString("Unable to canonicalize uri '%s': %s",
uri.ToCString(), error_obj.ToErrorCString());
} else {
- *error = zone->PrintToString("Unable to canonicalize uri '%s': "
- "library tag handler returned wrong type",
- uri.ToCString());
+ *error = zone->PrintToString(
+ "Unable to canonicalize uri '%s': "
+ "library tag handler returned wrong type",
+ uri.ToCString());
}
Dart_ExitScope();
} else {
@@ -348,7 +336,7 @@
if (Snapshot::IncludesCode(Dart::snapshot_kind())) {
const Array& args = Array::Handle(Array::New(1));
args.SetAt(0, String::Handle(String::New(
- "Isolate.spawnUri not supported under precompilation")));
+ "Isolate.spawnUri not supported under precompilation")));
Exceptions::ThrowByType(Exceptions::kUnsupported, args);
UNREACHABLE();
}
@@ -372,21 +360,11 @@
Dart_Port on_exit_port = onExit.IsNull() ? ILLEGAL_PORT : onExit.Id();
Dart_Port on_error_port = onError.IsNull() ? ILLEGAL_PORT : onError.Id();
- IsolateSpawnState* state =
- new IsolateSpawnState(
- port.Id(),
- isolate->init_callback_data(),
- canonical_uri,
- utf8_package_root,
- utf8_package_config,
- args,
- message,
- isolate->spawn_count_monitor(),
- isolate->spawn_count(),
- paused.value(),
- fatal_errors,
- on_exit_port,
- on_error_port);
+ IsolateSpawnState* state = new IsolateSpawnState(
+ port.Id(), isolate->init_callback_data(), canonical_uri,
+ utf8_package_root, utf8_package_config, args, message,
+ isolate->spawn_count_monitor(), isolate->spawn_count(), paused.value(),
+ fatal_errors, on_exit_port, on_error_port);
// If we were passed a value then override the default flags state for
// checked mode.
@@ -423,17 +401,17 @@
DEFINE_NATIVE_ENTRY(Isolate_getPortAndCapabilitiesOfCurrentIsolate, 0) {
const Array& result = Array::Handle(Array::New(3));
result.SetAt(0, SendPort::Handle(SendPort::New(isolate->main_port())));
- result.SetAt(1, Capability::Handle(
- Capability::New(isolate->pause_capability())));
- result.SetAt(2, Capability::Handle(
- Capability::New(isolate->terminate_capability())));
+ result.SetAt(
+ 1, Capability::Handle(Capability::New(isolate->pause_capability())));
+ result.SetAt(
+ 2, Capability::Handle(Capability::New(isolate->terminate_capability())));
return result.raw();
}
DEFINE_NATIVE_ENTRY(Isolate_getCurrentRootUriStr, 0) {
- const Library& root_lib = Library::Handle(zone,
- isolate->object_store()->root_library());
+ const Library& root_lib =
+ Library::Handle(zone, isolate->object_store()->root_library());
return root_lib.url();
}
@@ -449,8 +427,7 @@
MessageWriter writer(&data, &allocator, false);
writer.WriteMessage(msg);
- PortMap::PostMessage(new Message(port.Id(),
- data, writer.BytesWritten(),
+ PortMap::PostMessage(new Message(port.Id(), data, writer.BytesWritten(),
Message::kOOBPriority));
return Object::null();
}
diff --git a/runtime/lib/libgen_in.cc b/runtime/lib/libgen_in.cc
index 4e10df6..ba6f4df 100644
--- a/runtime/lib/libgen_in.cc
+++ b/runtime/lib/libgen_in.cc
@@ -2,6 +2,8 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
+// clang-format off
+
#include "{{INCLUDE}}" // NOLINT
// This file is used to generate the mapping of libraries which have
diff --git a/runtime/lib/linked_hash_map.cc b/runtime/lib/linked_hash_map.cc
index bc128c7..7c96ed4 100644
--- a/runtime/lib/linked_hash_map.cc
+++ b/runtime/lib/linked_hash_map.cc
@@ -23,8 +23,7 @@
DEFINE_NATIVE_ENTRY(LinkedHashMap_setIndex, 2) {
const LinkedHashMap& map =
LinkedHashMap::CheckedHandle(arguments->NativeArgAt(0));
- const TypedData& index =
- TypedData::CheckedHandle(arguments->NativeArgAt(1));
+ const TypedData& index = TypedData::CheckedHandle(arguments->NativeArgAt(1));
map.SetIndex(index);
return Object::null();
}
@@ -40,8 +39,7 @@
DEFINE_NATIVE_ENTRY(LinkedHashMap_setData, 2) {
const LinkedHashMap& map =
LinkedHashMap::CheckedHandle(arguments->NativeArgAt(0));
- const Array& data =
- Array::CheckedHandle(arguments->NativeArgAt(1));
+ const Array& data = Array::CheckedHandle(arguments->NativeArgAt(1));
map.SetData(data);
return Object::null();
}
@@ -57,8 +55,7 @@
DEFINE_NATIVE_ENTRY(LinkedHashMap_setHashMask, 2) {
const LinkedHashMap& map =
LinkedHashMap::CheckedHandle(arguments->NativeArgAt(0));
- const Smi& hashMask =
- Smi::CheckedHandle(arguments->NativeArgAt(1));
+ const Smi& hashMask = Smi::CheckedHandle(arguments->NativeArgAt(1));
map.SetHashMask(hashMask.Value());
return Object::null();
}
@@ -74,8 +71,7 @@
DEFINE_NATIVE_ENTRY(LinkedHashMap_setDeletedKeys, 2) {
const LinkedHashMap& map =
LinkedHashMap::CheckedHandle(arguments->NativeArgAt(0));
- const Smi& deletedKeys =
- Smi::CheckedHandle(arguments->NativeArgAt(1));
+ const Smi& deletedKeys = Smi::CheckedHandle(arguments->NativeArgAt(1));
map.SetDeletedKeys(deletedKeys.Value());
return Object::null();
}
@@ -91,8 +87,7 @@
DEFINE_NATIVE_ENTRY(LinkedHashMap_setUsedData, 2) {
const LinkedHashMap& map =
LinkedHashMap::CheckedHandle(arguments->NativeArgAt(0));
- const Smi& usedData =
- Smi::CheckedHandle(arguments->NativeArgAt(1));
+ const Smi& usedData = Smi::CheckedHandle(arguments->NativeArgAt(1));
map.SetUsedData(usedData.Value());
return Object::null();
}
diff --git a/runtime/lib/math.cc b/runtime/lib/math.cc
index 0199782..d95e32f 100644
--- a/runtime/lib/math.cc
+++ b/runtime/lib/math.cc
@@ -68,8 +68,8 @@
DEFINE_NATIVE_ENTRY(Math_doublePow, 2) {
const double operand =
Double::CheckedHandle(arguments->NativeArgAt(0)).value();
- GET_NON_NULL_NATIVE_ARGUMENT(
- Double, exponent_object, arguments->NativeArgAt(1));
+ GET_NON_NULL_NATIVE_ARGUMENT(Double, exponent_object,
+ arguments->NativeArgAt(1));
const double exponent = exponent_object.value();
return Double::New(pow(operand, exponent));
}
@@ -106,14 +106,14 @@
uint64_t state = (A * state_lo) + state_hi;
array.SetUint32(0, static_cast<uint32_t>(state));
array.SetUint32(array.ElementSizeInBytes(),
- static_cast<uint32_t>(state >> 32));
+ static_cast<uint32_t>(state >> 32));
return Object::null();
}
RawTypedData* CreateRandomState(Zone* zone, uint64_t seed) {
- const TypedData& result = TypedData::Handle(
- zone, TypedData::New(kTypedDataUint32ArrayCid, 2));
+ const TypedData& result =
+ TypedData::Handle(zone, TypedData::New(kTypedDataUint32ArrayCid, 2));
result.SetUint32(0, static_cast<uint32_t>(seed));
result.SetUint32(result.ElementSizeInBytes(),
static_cast<uint32_t>(seed >> 32));
@@ -125,11 +125,11 @@
// Thomas Wang 64-bit mix.
// http://www.concentric.net/~Ttwang/tech/inthash.htm
// via. http://web.archive.org/web/20071223173210/http://www.concentric.net/~Ttwang/tech/inthash.htm
- n = (~n) + (n << 21); // n = (n << 21) - n - 1;
+ n = (~n) + (n << 21); // n = (n << 21) - n - 1;
n = n ^ (n >> 24);
- n = n * 265; // n = (n + (n << 3)) + (n << 8);
+ n = n * 265; // n = (n + (n << 3)) + (n << 8);
n = n ^ (n >> 14);
- n = n * 21; // n = (n + (n << 2)) + (n << 4);
+ n = n * 21; // n = (n + (n << 2)) + (n << 4);
n = n ^ (n >> 28);
n = n + (n << 31);
return n;
diff --git a/runtime/lib/mirrors.cc b/runtime/lib/mirrors.cc
index 611c3d3..48e579b 100644
--- a/runtime/lib/mirrors.cc
+++ b/runtime/lib/mirrors.cc
@@ -24,18 +24,15 @@
#define PROPAGATE_IF_MALFORMED(type) \
if (type.IsMalformed()) { \
Exceptions::PropagateError(Error::Handle(type.error())); \
- } \
+ }
static RawInstance* CreateMirror(const String& mirror_class_name,
const Array& constructor_arguments) {
const Library& mirrors_lib = Library::Handle(Library::MirrorsLibrary());
const String& constructor_name = Symbols::Dot();
- const Object& result = Object::Handle(
- DartLibraryCalls::InstanceCreate(mirrors_lib,
- mirror_class_name,
- constructor_name,
- constructor_arguments));
+ const Object& result = Object::Handle(DartLibraryCalls::InstanceCreate(
+ mirrors_lib, mirror_class_name, constructor_name, constructor_arguments));
ASSERT(!result.IsError());
return Instance::Cast(result).raw();
}
@@ -53,8 +50,8 @@
const Array& argument_names,
const InvocationMirror::Call call,
const InvocationMirror::Type type) {
- const Smi& invocation_type = Smi::Handle(Smi::New(
- InvocationMirror::EncodeType(call, type)));
+ const Smi& invocation_type =
+ Smi::Handle(Smi::New(InvocationMirror::EncodeType(call, type)));
const Array& args = Array::Handle(Array::New(6));
args.SetAt(0, receiver);
@@ -73,12 +70,12 @@
}
const Library& libcore = Library::Handle(Library::CoreLibrary());
- const Class& NoSuchMethodError = Class::Handle(
- libcore.LookupClass(Symbols::NoSuchMethodError()));
+ const Class& NoSuchMethodError =
+ Class::Handle(libcore.LookupClass(Symbols::NoSuchMethodError()));
const Function& throwNew = Function::Handle(
NoSuchMethodError.LookupFunctionAllowPrivate(Symbols::ThrowNew()));
- const Object& result = Object::Handle(
- DartEntry::InvokeFunction(throwNew, args));
+ const Object& result =
+ Object::Handle(DartEntry::InvokeFunction(throwNew, args));
ASSERT(result.IsError());
Exceptions::PropagateError(Error::Cast(result));
UNREACHABLE();
@@ -98,8 +95,8 @@
UNREACHABLE();
}
if (!func.HasCode()) {
- const Error& error = Error::Handle(
- zone, Compiler::CompileFunction(thread, func));
+ const Error& error =
+ Error::Handle(zone, Compiler::CompileFunction(thread, func));
if (!error.IsNull()) {
Exceptions::PropagateError(error);
UNREACHABLE();
@@ -111,8 +108,8 @@
const Instance& owner_mirror) {
HANDLESCOPE(Thread::Current());
const intptr_t implicit_param_count = func.NumImplicitParameters();
- const intptr_t non_implicit_param_count = func.NumParameters() -
- implicit_param_count;
+ const intptr_t non_implicit_param_count =
+ func.NumParameters() - implicit_param_count;
const intptr_t index_of_first_optional_param =
non_implicit_param_count - func.NumOptionalParameters();
const intptr_t index_of_first_named_param =
@@ -178,11 +175,11 @@
name ^= func.ParameterNameAt(implicit_param_count + i);
if (has_extra_parameter_info) {
is_final ^= param_descriptor.At(i * Parser::kParameterEntrySize +
- Parser::kParameterIsFinalOffset);
+ Parser::kParameterIsFinalOffset);
default_value = param_descriptor.At(i * Parser::kParameterEntrySize +
- Parser::kParameterDefaultValueOffset);
+ Parser::kParameterDefaultValueOffset);
metadata = param_descriptor.At(i * Parser::kParameterEntrySize +
- Parser::kParameterMetadataOffset);
+ Parser::kParameterMetadataOffset);
}
ASSERT(default_value.IsNull() || default_value.IsInstance());
@@ -278,15 +275,15 @@
intptr_t kind_flags = 0;
kind_flags |= (func.is_abstract() << Mirrors::kAbstract);
- kind_flags |= (func.IsGetterFunction() << Mirrors::kGetter);
- kind_flags |= (func.IsSetterFunction() << Mirrors::kSetter);
+ kind_flags |= (func.IsGetterFunction() << Mirrors::kGetter);
+ kind_flags |= (func.IsSetterFunction() << Mirrors::kSetter);
bool is_ctor = (func.kind() == RawFunction::kConstructor);
- kind_flags |= (is_ctor << Mirrors::kConstructor);
+ kind_flags |= (is_ctor << Mirrors::kConstructor);
kind_flags |= ((is_ctor && func.is_const()) << Mirrors::kConstCtor);
- kind_flags |= ((is_ctor && func.IsGenerativeConstructor())
- << Mirrors::kGenerativeCtor);
- kind_flags |= ((is_ctor && func.is_redirecting())
- << Mirrors::kRedirectingCtor);
+ kind_flags |=
+ ((is_ctor && func.IsGenerativeConstructor()) << Mirrors::kGenerativeCtor);
+ kind_flags |=
+ ((is_ctor && func.is_redirecting()) << Mirrors::kRedirectingCtor);
kind_flags |= ((is_ctor && func.IsFactory()) << Mirrors::kFactoryCtor);
kind_flags |= (func.is_external() << Mirrors::kExternal);
args.SetAt(5, Smi::Handle(Smi::New(kind_flags)));
@@ -364,10 +361,7 @@
args.SetAt(1, str);
str = lib.url();
const char* censored_libraries[] = {
- "dart:_builtin",
- "dart:_blink",
- "dart:_vmservice",
- NULL,
+ "dart:_builtin", "dart:_blink", "dart:_vmservice", NULL,
};
for (intptr_t i = 0; censored_libraries[i] != NULL; i++) {
if (str.Equals(censored_libraries[i])) {
@@ -378,8 +372,8 @@
if (str.Equals("dart:io")) {
// Hack around dart:io being loaded into non-service isolates in Dartium.
Isolate* isolate = thread->isolate();
- const GrowableObjectArray& libraries = GrowableObjectArray::Handle(
- zone, isolate->object_store()->libraries());
+ const GrowableObjectArray& libraries =
+ GrowableObjectArray::Handle(zone, isolate->object_store()->libraries());
Library& other_lib = Library::Handle(zone);
String& other_uri = String::Handle(zone);
for (intptr_t i = 0; i < libraries.Length(); i++) {
@@ -483,8 +477,8 @@
for (intptr_t i = 0; i < ports.Length(); i++) {
ns ^= ports.At(i);
if (!ns.IsNull()) {
- dep = CreateLibraryDependencyMirror(
- thread, lib_mirror, ns, prefix, true, false);
+ dep = CreateLibraryDependencyMirror(thread, lib_mirror, ns, prefix, true,
+ false);
if (!dep.IsNull()) {
deps.Add(dep);
}
@@ -495,8 +489,8 @@
ports = lib.exports();
for (intptr_t i = 0; i < ports.Length(); i++) {
ns ^= ports.At(i);
- dep = CreateLibraryDependencyMirror(
- thread, lib_mirror, ns, prefix, false, false);
+ dep = CreateLibraryDependencyMirror(thread, lib_mirror, ns, prefix, false,
+ false);
if (!dep.IsNull()) {
deps.Add(dep);
}
@@ -513,8 +507,8 @@
for (intptr_t i = 0; i < ports.Length(); i++) {
ns ^= ports.At(i);
if (!ns.IsNull()) {
- dep = CreateLibraryDependencyMirror(
- thread, lib_mirror, ns, prefix, true, prefix.is_deferred_load());
+ dep = CreateLibraryDependencyMirror(thread, lib_mirror, ns, prefix,
+ true, prefix.is_deferred_load());
if (!dep.IsNull()) {
deps.Add(dep);
}
@@ -541,8 +535,8 @@
if (type.IsFunctionType()) {
const Class& scope_class = Class::Handle(Type::Cast(type).type_class());
if (scope_class.IsTypedefClass()) {
- return CreateTypedefMirror(scope_class,
- type, Bool::False(), Object::null_instance());
+ return CreateTypedefMirror(scope_class, type, Bool::False(),
+ Object::null_instance());
} else {
return CreateFunctionTypeMirror(type);
}
@@ -577,8 +571,8 @@
Thread* thread = Thread::Current();
Isolate* isolate = thread->isolate();
const String& debug_name = String::Handle(String::New(isolate->name()));
- const Library& root_library = Library::Handle(thread->zone(),
- isolate->object_store()->root_library());
+ const Library& root_library =
+ Library::Handle(thread->zone(), isolate->object_store()->root_library());
const Instance& root_library_mirror =
Instance::Handle(CreateLibraryMirror(thread, root_library));
@@ -594,21 +588,21 @@
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
const Library& lib = Library::Handle(zone, Library::MirrorsLibrary());
- const Class& cls = Class::Handle(zone,
- lib.LookupClassAllowPrivate(Symbols::_LocalMethodMirror()));
+ const Class& cls = Class::Handle(
+ zone, lib.LookupClassAllowPrivate(Symbols::_LocalMethodMirror()));
const Error& error = Error::Handle(zone, cls.EnsureIsFinalized(thread));
ASSERT(error.IsNull());
Field& field = Field::Handle();
Smi& value = Smi::Handle();
- #define CHECK_KIND_SHIFT(name) \
- field = cls.LookupField(String::Handle(String::New(#name))); \
- ASSERT(!field.IsNull()); \
- value ^= field.StaticValue(); \
- ASSERT(value.Value() == Mirrors::name);
+#define CHECK_KIND_SHIFT(name) \
+ field = cls.LookupField(String::Handle(String::New(#name))); \
+ ASSERT(!field.IsNull()); \
+ value ^= field.StaticValue(); \
+ ASSERT(value.Value() == Mirrors::name);
MIRRORS_KIND_SHIFT_LIST(CHECK_KIND_SHIFT)
- #undef CHECK_KIND_SHIFT
+#undef CHECK_KIND_SHIFT
#endif
}
@@ -628,27 +622,21 @@
// Invoke the function, or noSuchMethod if it is null. Propagate any unhandled
// exceptions. Wrap and propagate any compilation errors.
-static RawInstance* InvokeDynamicFunction(
- const Instance& receiver,
- const Function& function,
- const String& target_name,
- const Array& args,
- const Array& args_descriptor_array) {
+static RawInstance* InvokeDynamicFunction(const Instance& receiver,
+ const Function& function,
+ const String& target_name,
+ const Array& args,
+ const Array& args_descriptor_array) {
// Note "args" is already the internal arguments with the receiver as the
// first element.
Object& result = Object::Handle();
ArgumentsDescriptor args_descriptor(args_descriptor_array);
- if (function.IsNull() ||
- !function.is_reflectable() ||
+ if (function.IsNull() || !function.is_reflectable() ||
!function.AreValidArguments(args_descriptor, NULL)) {
- result = DartEntry::InvokeNoSuchMethod(receiver,
- target_name,
- args,
+ result = DartEntry::InvokeNoSuchMethod(receiver, target_name, args,
args_descriptor_array);
} else {
- result = DartEntry::InvokeFunction(function,
- args,
- args_descriptor_array);
+ result = DartEntry::InvokeFunction(function, args, args_descriptor_array);
}
return ReturnResult(result);
}
@@ -661,8 +649,7 @@
// The getter function may either be in the library or in the field's owner
// class, depending on whether it was an actual getter, or an uninitialized
// field.
- const Field& field = Field::Handle(
- library.LookupLocalField(getter_name));
+ const Field& field = Field::Handle(library.LookupLocalField(getter_name));
Function& getter = Function::Handle();
if (field.IsNull()) {
// No field found. Check for a getter in the lib.
@@ -698,13 +685,9 @@
}
if (throw_nsm_if_absent) {
- ThrowNoSuchMethod(Instance::null_instance(),
- getter_name,
- getter,
- Object::null_array(),
- Object::null_array(),
- InvocationMirror::kTopLevel,
- InvocationMirror::kGetter);
+ ThrowNoSuchMethod(Instance::null_instance(), getter_name, getter,
+ Object::null_array(), Object::null_array(),
+ InvocationMirror::kTopLevel, InvocationMirror::kGetter);
UNREACHABLE();
}
@@ -719,13 +702,12 @@
const String& getter_name,
const bool throw_nsm_if_absent) {
// Note static fields do not have implicit getters.
- const Field& field =
- Field::Handle(klass.LookupStaticField(getter_name));
+ const Field& field = Field::Handle(klass.LookupStaticField(getter_name));
if (field.IsNull() || field.IsUninitialized()) {
- const String& internal_getter_name = String::Handle(
- Field::GetterName(getter_name));
- Function& getter = Function::Handle(
- klass.LookupStaticFunction(internal_getter_name));
+ const String& internal_getter_name =
+ String::Handle(Field::GetterName(getter_name));
+ Function& getter =
+ Function::Handle(klass.LookupStaticFunction(internal_getter_name));
if (getter.IsNull() || !getter.is_reflectable()) {
if (getter.IsNull()) {
@@ -738,13 +720,9 @@
}
}
if (throw_nsm_if_absent) {
- ThrowNoSuchMethod(AbstractType::Handle(klass.RareType()),
- getter_name,
- getter,
- Object::null_array(),
- Object::null_array(),
- InvocationMirror::kStatic,
- InvocationMirror::kGetter);
+ ThrowNoSuchMethod(AbstractType::Handle(klass.RareType()), getter_name,
+ getter, Object::null_array(), Object::null_array(),
+ InvocationMirror::kStatic, InvocationMirror::kGetter);
UNREACHABLE();
}
// Fall through case: Indicate that we didn't find any function or field
@@ -791,8 +769,8 @@
DEFINE_NATIVE_ENTRY(MirrorSystem_libraries, 0) {
- const GrowableObjectArray& libraries = GrowableObjectArray::Handle(
- zone, isolate->object_store()->libraries());
+ const GrowableObjectArray& libraries =
+ GrowableObjectArray::Handle(zone, isolate->object_store()->libraries());
const intptr_t num_libraries = libraries.Length();
const GrowableObjectArray& library_mirrors = GrowableObjectArray::Handle(
@@ -829,8 +807,7 @@
Exceptions::ThrowArgumentError(type);
UNREACHABLE();
}
- return CreateClassMirror(cls,
- AbstractType::Handle(cls.DeclarationType()),
+ return CreateClassMirror(cls, AbstractType::Handle(cls.DeclarationType()),
Bool::True(), // is_declaration
Object::null_instance());
}
@@ -899,8 +876,7 @@
DEFINE_NATIVE_ENTRY(FunctionTypeMirror_call_method, 2) {
- GET_NON_NULL_NATIVE_ARGUMENT(Instance,
- owner_mirror,
+ GET_NON_NULL_NATIVE_ARGUMENT(Instance, owner_mirror,
arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1));
// TODO(rmacnak): Return get:call() method on class _Closure instead?
@@ -921,8 +897,7 @@
DEFINE_NATIVE_ENTRY(FunctionTypeMirror_return_type, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(0));
- GET_NON_NULL_NATIVE_ARGUMENT(AbstractType,
- instantiator,
+ GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, instantiator,
arguments->NativeArgAt(1));
const Function& func = Function::Handle(ref.GetFunctionReferent());
ASSERT(!func.IsNull());
@@ -1011,8 +986,7 @@
DEFINE_NATIVE_ENTRY(ClassMirror_mixin_instantiated, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, type, arguments->NativeArgAt(0));
- GET_NON_NULL_NATIVE_ARGUMENT(AbstractType,
- instantiator,
+ GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, instantiator,
arguments->NativeArgAt(1));
PROPAGATE_IF_MALFORMED(type);
ASSERT(type.IsFinalized());
@@ -1027,11 +1001,9 @@
DEFINE_NATIVE_ENTRY(ClassMirror_members, 3) {
- GET_NON_NULL_NATIVE_ARGUMENT(Instance,
- owner_mirror,
+ GET_NON_NULL_NATIVE_ARGUMENT(Instance, owner_mirror,
arguments->NativeArgAt(0));
- GET_NATIVE_ARGUMENT(AbstractType,
- owner_instantiator,
+ GET_NATIVE_ARGUMENT(AbstractType, owner_instantiator,
arguments->NativeArgAt(1));
GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(2));
const Class& klass = Class::Handle(ref.GetClassReferent());
@@ -1065,10 +1037,10 @@
func ^= functions.At(i);
if (func.is_reflectable() &&
(func.kind() == RawFunction::kRegularFunction ||
- func.kind() == RawFunction::kGetterFunction ||
- func.kind() == RawFunction::kSetterFunction)) {
- member_mirror = CreateMethodMirror(func, owner_mirror,
- owner_instantiator);
+ func.kind() == RawFunction::kGetterFunction ||
+ func.kind() == RawFunction::kSetterFunction)) {
+ member_mirror =
+ CreateMethodMirror(func, owner_mirror, owner_instantiator);
member_mirrors.Add(member_mirror);
}
}
@@ -1078,11 +1050,9 @@
DEFINE_NATIVE_ENTRY(ClassMirror_constructors, 3) {
- GET_NON_NULL_NATIVE_ARGUMENT(Instance,
- owner_mirror,
+ GET_NON_NULL_NATIVE_ARGUMENT(Instance, owner_mirror,
arguments->NativeArgAt(0));
- GET_NATIVE_ARGUMENT(AbstractType,
- owner_instantiator,
+ GET_NATIVE_ARGUMENT(AbstractType, owner_instantiator,
arguments->NativeArgAt(1));
GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(2));
const Class& klass = Class::Handle(ref.GetClassReferent());
@@ -1096,15 +1066,15 @@
const intptr_t num_functions = functions.Length();
Instance& constructor_mirror = Instance::Handle();
- const GrowableObjectArray& constructor_mirrors = GrowableObjectArray::Handle(
- GrowableObjectArray::New(num_functions));
+ const GrowableObjectArray& constructor_mirrors =
+ GrowableObjectArray::Handle(GrowableObjectArray::New(num_functions));
Function& func = Function::Handle();
for (intptr_t i = 0; i < num_functions; i++) {
func ^= functions.At(i);
if (func.is_reflectable() && func.kind() == RawFunction::kConstructor) {
- constructor_mirror = CreateMethodMirror(func, owner_mirror,
- owner_instantiator);
+ constructor_mirror =
+ CreateMethodMirror(func, owner_mirror, owner_instantiator);
constructor_mirrors.Add(constructor_mirror);
}
}
@@ -1114,8 +1084,7 @@
DEFINE_NATIVE_ENTRY(LibraryMirror_members, 2) {
- GET_NON_NULL_NATIVE_ARGUMENT(Instance,
- owner_mirror,
+ GET_NON_NULL_NATIVE_ARGUMENT(Instance, owner_mirror,
arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1));
const Library& library = Library::Handle(ref.GetLibraryReferent());
@@ -1139,8 +1108,7 @@
// mixin applications.
if (!klass.IsDynamicClass() && !klass.IsMixinApplication()) {
type = klass.DeclarationType();
- member_mirror = CreateClassMirror(klass,
- type,
+ member_mirror = CreateClassMirror(klass, type,
Bool::True(), // is_declaration
owner_mirror);
member_mirrors.Add(member_mirror);
@@ -1155,10 +1123,10 @@
const Function& func = Function::Cast(entry);
if (func.is_reflectable() &&
(func.kind() == RawFunction::kRegularFunction ||
- func.kind() == RawFunction::kGetterFunction ||
- func.kind() == RawFunction::kSetterFunction)) {
- member_mirror = CreateMethodMirror(func, owner_mirror,
- AbstractType::Handle());
+ func.kind() == RawFunction::kGetterFunction ||
+ func.kind() == RawFunction::kSetterFunction)) {
+ member_mirror =
+ CreateMethodMirror(func, owner_mirror, AbstractType::Handle());
member_mirrors.Add(member_mirror);
}
}
@@ -1222,8 +1190,7 @@
GET_NON_NULL_NATIVE_ARGUMENT(TypeParameter, param, arguments->NativeArgAt(0));
const Class& owner = Class::Handle(param.parameterized_class());
const AbstractType& type = AbstractType::Handle(owner.DeclarationType());
- return CreateClassMirror(owner,
- type,
+ return CreateClassMirror(owner, type,
Bool::True(), // is_declaration
Instance::null_instance());
}
@@ -1259,10 +1226,8 @@
}
}
ASSERT(!ctxt_library.IsNull());
- const Object& result =
- Object::Handle(ctxt_library.Evaluate(expression,
- Array::empty_array(),
- Array::empty_array()));
+ const Object& result = Object::Handle(ctxt_library.Evaluate(
+ expression, Array::empty_array(), Array::empty_array()));
if (result.IsError()) {
Exceptions::PropagateError(Error::Cast(result));
UNREACHABLE();
@@ -1285,8 +1250,7 @@
ASSERT(type.IsFunctionType());
const Class& cls = Class::Handle(type.type_class());
ASSERT(cls.IsTypedefClass());
- return CreateTypedefMirror(cls,
- AbstractType::Handle(cls.DeclarationType()),
+ return CreateTypedefMirror(cls, AbstractType::Handle(cls.DeclarationType()),
Bool::True(), // is_declaration
Object::null_instance());
}
@@ -1296,14 +1260,14 @@
// because this native is an instance method in order to be polymorphic
// with its cousins.
GET_NATIVE_ARGUMENT(Instance, reflectee, arguments->NativeArgAt(1));
- GET_NON_NULL_NATIVE_ARGUMENT(
- String, function_name, arguments->NativeArgAt(2));
+ GET_NON_NULL_NATIVE_ARGUMENT(String, function_name,
+ arguments->NativeArgAt(2));
GET_NON_NULL_NATIVE_ARGUMENT(Array, args, arguments->NativeArgAt(3));
GET_NON_NULL_NATIVE_ARGUMENT(Array, arg_names, arguments->NativeArgAt(4));
Class& klass = Class::Handle(reflectee.clazz());
- Function& function = Function::Handle(zone,
- Resolver::ResolveDynamicAnyArgs(zone, klass, function_name));
+ Function& function = Function::Handle(
+ zone, Resolver::ResolveDynamicAnyArgs(zone, klass, function_name));
const Array& args_descriptor =
Array::Handle(zone, ArgumentsDescriptor::New(args.Length(), arg_names));
@@ -1321,12 +1285,9 @@
getter_args.SetAt(0, reflectee);
const Array& getter_args_descriptor =
Array::Handle(zone, ArgumentsDescriptor::New(getter_args.Length()));
- const Instance& getter_result = Instance::Handle(zone,
- InvokeDynamicFunction(reflectee,
- function,
- getter_name,
- getter_args,
- getter_args_descriptor));
+ const Instance& getter_result = Instance::Handle(
+ zone, InvokeDynamicFunction(reflectee, function, getter_name,
+ getter_args, getter_args_descriptor));
// Replace the closure as the receiver in the arguments list.
args.SetAt(0, getter_result);
// Call the closure.
@@ -1341,10 +1302,7 @@
}
// Found an ordinary method.
- return InvokeDynamicFunction(reflectee,
- function,
- function_name,
- args,
+ return InvokeDynamicFunction(reflectee, function, function_name, args,
args_descriptor);
}
@@ -1357,17 +1315,17 @@
GET_NON_NULL_NATIVE_ARGUMENT(String, getter_name, arguments->NativeArgAt(2));
Class& klass = Class::Handle(reflectee.clazz());
- const String& internal_getter_name = String::Handle(
- Field::GetterName(getter_name));
- Function& function = Function::Handle(zone,
- Resolver::ResolveDynamicAnyArgs(zone, klass, internal_getter_name));
+ const String& internal_getter_name =
+ String::Handle(Field::GetterName(getter_name));
+ Function& function = Function::Handle(
+ zone, Resolver::ResolveDynamicAnyArgs(zone, klass, internal_getter_name));
// Check for method extraction when method extractors are not created.
if (function.IsNull() && !FLAG_lazy_dispatchers) {
function = Resolver::ResolveDynamicAnyArgs(zone, klass, getter_name);
if (!function.IsNull()) {
const Function& closure_function =
- Function::Handle(zone, function.ImplicitClosureFunction());
+ Function::Handle(zone, function.ImplicitClosureFunction());
return closure_function.ImplicitInstanceClosure(reflectee);
}
}
@@ -1379,10 +1337,7 @@
Array::Handle(zone, ArgumentsDescriptor::New(args.Length()));
// InvokeDynamic invokes NoSuchMethod if the provided function is null.
- return InvokeDynamicFunction(reflectee,
- function,
- internal_getter_name,
- args,
+ return InvokeDynamicFunction(reflectee, function, internal_getter_name, args,
args_descriptor);
}
@@ -1398,8 +1353,8 @@
const Class& klass = Class::Handle(zone, reflectee.clazz());
const String& internal_setter_name =
String::Handle(zone, Field::SetterName(setter_name));
- const Function& setter = Function::Handle(zone,
- Resolver::ResolveDynamicAnyArgs(zone, klass, internal_setter_name));
+ const Function& setter = Function::Handle(
+ zone, Resolver::ResolveDynamicAnyArgs(zone, klass, internal_setter_name));
const int kNumArgs = 2;
const Array& args = Array::Handle(zone, Array::New(kNumArgs));
@@ -1408,10 +1363,7 @@
const Array& args_descriptor =
Array::Handle(zone, ArgumentsDescriptor::New(args.Length()));
- return InvokeDynamicFunction(reflectee,
- setter,
- internal_setter_name,
- args,
+ return InvokeDynamicFunction(reflectee, setter, internal_setter_name, args,
args_descriptor);
}
@@ -1449,8 +1401,7 @@
instantiator = Type::New(cls, arguments, TokenPosition::kNoSource);
instantiator.SetIsFinalized();
}
- return CreateMethodMirror(function,
- Instance::null_instance(),
+ return CreateMethodMirror(function, Instance::null_instance(),
instantiator);
}
return Instance::null();
@@ -1463,8 +1414,8 @@
// with its cousins.
GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1));
const Class& klass = Class::Handle(ref.GetClassReferent());
- GET_NON_NULL_NATIVE_ARGUMENT(
- String, function_name, arguments->NativeArgAt(2));
+ GET_NON_NULL_NATIVE_ARGUMENT(String, function_name,
+ arguments->NativeArgAt(2));
GET_NON_NULL_NATIVE_ARGUMENT(Array, args, arguments->NativeArgAt(3));
GET_NON_NULL_NATIVE_ARGUMENT(Array, arg_names, arguments->NativeArgAt(4));
@@ -1474,8 +1425,8 @@
UNREACHABLE();
}
- Function& function = Function::Handle(
- klass.LookupStaticFunction(function_name));
+ Function& function =
+ Function::Handle(klass.LookupStaticFunction(function_name));
if (function.IsNull()) {
// Didn't find a method: try to find a getter and invoke call on its result.
@@ -1499,8 +1450,8 @@
call_args.SetAt(i + 1, temp);
}
call_args.SetAt(0, getter_result);
- const Array& call_args_descriptor_array =
- Array::Handle(ArgumentsDescriptor::New(call_args.Length(), arg_names));
+ const Array& call_args_descriptor_array = Array::Handle(
+ ArgumentsDescriptor::New(call_args.Length(), arg_names));
// Call the closure.
const Object& call_result = Object::Handle(
DartEntry::InvokeClosure(call_args, call_args_descriptor_array));
@@ -1517,15 +1468,10 @@
ArgumentsDescriptor args_descriptor(args_descriptor_array);
- if (function.IsNull() ||
- !function.AreValidArguments(args_descriptor, NULL) ||
+ if (function.IsNull() || !function.AreValidArguments(args_descriptor, NULL) ||
!function.is_reflectable()) {
- ThrowNoSuchMethod(AbstractType::Handle(klass.RareType()),
- function_name,
- function,
- args,
- arg_names,
- InvocationMirror::kStatic,
+ ThrowNoSuchMethod(AbstractType::Handle(klass.RareType()), function_name,
+ function, args, arg_names, InvocationMirror::kStatic,
InvocationMirror::kMethod);
UNREACHABLE();
}
@@ -1572,11 +1518,10 @@
}
// Check for real fields and user-defined setters.
- const Field& field =
- Field::Handle(klass.LookupStaticField(setter_name));
+ const Field& field = Field::Handle(klass.LookupStaticField(setter_name));
Function& setter = Function::Handle();
- const String& internal_setter_name = String::Handle(
- Field::SetterName(setter_name));
+ const String& internal_setter_name =
+ String::Handle(Field::SetterName(setter_name));
if (field.IsNull()) {
setter = klass.LookupStaticFunction(internal_setter_name);
@@ -1587,18 +1532,14 @@
if (setter.IsNull() || !setter.is_reflectable()) {
ThrowNoSuchMethod(AbstractType::Handle(klass.RareType()),
- internal_setter_name,
- setter,
- args,
- Object::null_array(),
- InvocationMirror::kStatic,
+ internal_setter_name, setter, args,
+ Object::null_array(), InvocationMirror::kStatic,
InvocationMirror::kSetter);
UNREACHABLE();
}
// Invoke the setter and return the result.
- Object& result = Object::Handle(
- DartEntry::InvokeFunction(setter, args));
+ Object& result = Object::Handle(DartEntry::InvokeFunction(setter, args));
if (result.IsError()) {
Exceptions::PropagateError(Error::Cast(result));
UNREACHABLE();
@@ -1612,12 +1553,8 @@
args.SetAt(0, value);
ThrowNoSuchMethod(AbstractType::Handle(klass.RareType()),
- internal_setter_name,
- setter,
- args,
- Object::null_array(),
- InvocationMirror::kStatic,
- InvocationMirror::kSetter);
+ internal_setter_name, setter, args, Object::null_array(),
+ InvocationMirror::kStatic, InvocationMirror::kSetter);
UNREACHABLE();
}
@@ -1630,8 +1567,8 @@
GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(0));
const Class& klass = Class::Handle(ref.GetClassReferent());
GET_NATIVE_ARGUMENT(Type, type, arguments->NativeArgAt(1));
- GET_NON_NULL_NATIVE_ARGUMENT(
- String, constructor_name, arguments->NativeArgAt(2));
+ GET_NON_NULL_NATIVE_ARGUMENT(String, constructor_name,
+ arguments->NativeArgAt(2));
GET_NON_NULL_NATIVE_ARGUMENT(Array, explicit_args, arguments->NativeArgAt(3));
GET_NON_NULL_NATIVE_ARGUMENT(Array, arg_names, arguments->NativeArgAt(4));
@@ -1655,18 +1592,15 @@
external_constructor_name = internal_constructor_name.raw();
}
- Function& lookup_constructor = Function::Handle(
- klass.LookupFunction(internal_constructor_name));
+ Function& lookup_constructor =
+ Function::Handle(klass.LookupFunction(internal_constructor_name));
if (lookup_constructor.IsNull() ||
(lookup_constructor.kind() != RawFunction::kConstructor) ||
!lookup_constructor.is_reflectable()) {
ThrowNoSuchMethod(AbstractType::Handle(klass.RareType()),
- external_constructor_name,
- lookup_constructor,
- explicit_args,
- arg_names,
- InvocationMirror::kConstructor,
+ external_constructor_name, lookup_constructor,
+ explicit_args, arg_names, InvocationMirror::kConstructor,
InvocationMirror::kMethod);
UNREACHABLE();
}
@@ -1730,19 +1664,15 @@
}
const Array& args_descriptor_array =
- Array::Handle(ArgumentsDescriptor::New(args.Length(),
- arg_names));
+ Array::Handle(ArgumentsDescriptor::New(args.Length(), arg_names));
ArgumentsDescriptor args_descriptor(args_descriptor_array);
if (!redirected_constructor.AreValidArguments(args_descriptor, NULL) ||
!redirected_constructor.is_reflectable()) {
external_constructor_name = redirected_constructor.name();
ThrowNoSuchMethod(AbstractType::Handle(klass.RareType()),
- external_constructor_name,
- redirected_constructor,
- explicit_args,
- arg_names,
- InvocationMirror::kConstructor,
+ external_constructor_name, redirected_constructor,
+ explicit_args, arg_names, InvocationMirror::kConstructor,
InvocationMirror::kMethod);
UNREACHABLE();
}
@@ -1766,10 +1696,8 @@
}
// Invoke the constructor and return the new object.
- const Object& result =
- Object::Handle(DartEntry::InvokeFunction(redirected_constructor,
- args,
- args_descriptor_array));
+ const Object& result = Object::Handle(DartEntry::InvokeFunction(
+ redirected_constructor, args, args_descriptor_array));
if (result.IsError()) {
Exceptions::PropagateError(Error::Cast(result));
UNREACHABLE();
@@ -1792,13 +1720,13 @@
// with its cousins.
GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1));
const Library& library = Library::Handle(ref.GetLibraryReferent());
- GET_NON_NULL_NATIVE_ARGUMENT(
- String, function_name, arguments->NativeArgAt(2));
+ GET_NON_NULL_NATIVE_ARGUMENT(String, function_name,
+ arguments->NativeArgAt(2));
GET_NON_NULL_NATIVE_ARGUMENT(Array, args, arguments->NativeArgAt(3));
GET_NON_NULL_NATIVE_ARGUMENT(Array, arg_names, arguments->NativeArgAt(4));
- Function& function = Function::Handle(
- library.LookupLocalFunction(function_name));
+ Function& function =
+ Function::Handle(library.LookupLocalFunction(function_name));
if (function.IsNull()) {
// Didn't find a method: try to find a getter and invoke call on its result.
@@ -1831,15 +1759,10 @@
Array::Handle(ArgumentsDescriptor::New(args.Length(), arg_names));
ArgumentsDescriptor args_descriptor(args_descriptor_array);
- if (function.IsNull() ||
- !function.AreValidArguments(args_descriptor, NULL) ||
+ if (function.IsNull() || !function.AreValidArguments(args_descriptor, NULL) ||
!function.is_reflectable()) {
- ThrowNoSuchMethod(Instance::null_instance(),
- function_name,
- function,
- args,
- arg_names,
- InvocationMirror::kTopLevel,
+ ThrowNoSuchMethod(Instance::null_instance(), function_name, function, args,
+ arg_names, InvocationMirror::kTopLevel,
InvocationMirror::kMethod);
UNREACHABLE();
}
@@ -1877,8 +1800,7 @@
// To access a top-level we may need to use the Field or the
// setter Function. The setter function may either be in the
// library or in the field's owner class, depending.
- const Field& field = Field::Handle(
- library.LookupLocalField(setter_name));
+ const Field& field = Field::Handle(library.LookupLocalField(setter_name));
Function& setter = Function::Handle();
const String& internal_setter_name =
String::Handle(Field::SetterName(setter_name));
@@ -1891,19 +1813,15 @@
args.SetAt(0, value);
if (setter.IsNull() || !setter.is_reflectable()) {
- ThrowNoSuchMethod(Instance::null_instance(),
- internal_setter_name,
- setter,
- args,
- Object::null_array(),
- InvocationMirror::kTopLevel,
+ ThrowNoSuchMethod(Instance::null_instance(), internal_setter_name, setter,
+ args, Object::null_array(), InvocationMirror::kTopLevel,
InvocationMirror::kSetter);
UNREACHABLE();
}
// Invoke the setter and return the result.
- const Object& result = Object::Handle(
- DartEntry::InvokeFunction(setter, args));
+ const Object& result =
+ Object::Handle(DartEntry::InvokeFunction(setter, args));
if (result.IsError()) {
Exceptions::PropagateError(Error::Cast(result));
UNREACHABLE();
@@ -1916,12 +1834,8 @@
const Array& args = Array::Handle(Array::New(kNumArgs));
args.SetAt(0, value);
- ThrowNoSuchMethod(Instance::null_instance(),
- internal_setter_name,
- setter,
- args,
- Object::null_array(),
- InvocationMirror::kTopLevel,
+ ThrowNoSuchMethod(Instance::null_instance(), internal_setter_name, setter,
+ args, Object::null_array(), InvocationMirror::kTopLevel,
InvocationMirror::kSetter);
UNREACHABLE();
}
@@ -1936,8 +1850,8 @@
GET_NATIVE_ARGUMENT(AbstractType, instantiator, arguments->NativeArgAt(1));
const Function& func = Function::Handle(ref.GetFunctionReferent());
if (func.IsNonImplicitClosureFunction()) {
- return CreateMethodMirror(Function::Handle(
- func.parent_function()), Object::null_instance(), instantiator);
+ return CreateMethodMirror(Function::Handle(func.parent_function()),
+ Object::null_instance(), instantiator);
}
const Class& owner = Class::Handle(func.Owner());
if (owner.IsTopLevel()) {
@@ -2012,10 +1926,8 @@
} else if (decl.IsClass()) {
const Class& cls = Class::Cast(decl);
const bool is_typedef = cls.IsTypedefClass();
- if (cls.is_synthesized_class() &&
- !is_typedef &&
- !cls.is_mixin_app_alias() &&
- !cls.is_enum_class()) {
+ if (cls.is_synthesized_class() && !is_typedef &&
+ !cls.is_mixin_app_alias() && !cls.is_enum_class()) {
return Instance::null(); // Synthetic.
}
script = cls.script();
diff --git a/runtime/lib/mirrors.h b/runtime/lib/mirrors.h
index 31f0d22..d6a5398 100644
--- a/runtime/lib/mirrors.h
+++ b/runtime/lib/mirrors.h
@@ -11,22 +11,22 @@
class Mirrors : public AllStatic {
public:
- #define MIRRORS_KIND_SHIFT_LIST(V) \
- V(kAbstract) \
- V(kGetter) \
- V(kSetter) \
- V(kConstructor) \
- V(kConstCtor) \
- V(kGenerativeCtor) \
- V(kRedirectingCtor) \
- V(kFactoryCtor) \
- V(kExternal) \
+#define MIRRORS_KIND_SHIFT_LIST(V) \
+ V(kAbstract) \
+ V(kGetter) \
+ V(kSetter) \
+ V(kConstructor) \
+ V(kConstCtor) \
+ V(kGenerativeCtor) \
+ V(kRedirectingCtor) \
+ V(kFactoryCtor) \
+ V(kExternal)
// These offsets much be kept in sync with those in mirrors_impl.dart.
enum KindShifts {
- #define DEFINE_KIND_SHIFT_ENUM(name) name,
- MIRRORS_KIND_SHIFT_LIST(DEFINE_KIND_SHIFT_ENUM)
- #undef DEFINE_KIND_SHIFT_ENUM
+#define DEFINE_KIND_SHIFT_ENUM(name) name,
+ MIRRORS_KIND_SHIFT_LIST(DEFINE_KIND_SHIFT_ENUM)
+#undef DEFINE_KIND_SHIFT_ENUM
};
};
diff --git a/runtime/lib/object.cc b/runtime/lib/object.cc
index 530b210..276d0d2 100644
--- a/runtime/lib/object.cc
+++ b/runtime/lib/object.cc
@@ -73,8 +73,8 @@
GET_NON_NULL_NATIVE_ARGUMENT(String, member_name, arguments->NativeArgAt(2));
GET_NON_NULL_NATIVE_ARGUMENT(Smi, invocation_type, arguments->NativeArgAt(3));
GET_NON_NULL_NATIVE_ARGUMENT(Instance, func_args, arguments->NativeArgAt(4));
- GET_NON_NULL_NATIVE_ARGUMENT(
- Instance, func_named_args, arguments->NativeArgAt(5));
+ GET_NON_NULL_NATIVE_ARGUMENT(Instance, func_named_args,
+ arguments->NativeArgAt(5));
const Array& dart_arguments = Array::Handle(Array::New(6));
dart_arguments.SetAt(0, instance);
dart_arguments.SetAt(1, member_name);
@@ -176,9 +176,8 @@
ASSERT(!type.IsMalformed());
ASSERT(!type.IsMalbounded());
Error& bound_error = Error::Handle(zone, Error::null());
- const bool is_instance_of = instance.IsInstanceOf(type,
- instantiator_type_arguments,
- &bound_error);
+ const bool is_instance_of =
+ instance.IsInstanceOf(type, instantiator_type_arguments, &bound_error);
if (FLAG_trace_type_checks) {
const char* result_str = is_instance_of ? "true" : "false";
OS::Print("Native Object.instanceOf: result %s\n", result_str);
@@ -198,11 +197,11 @@
StackFrame* caller_frame = iterator.NextFrame();
ASSERT(caller_frame != NULL);
const TokenPosition location = caller_frame->GetTokenPos();
- String& bound_error_message = String::Handle(
- zone, String::New(bound_error.ToErrorCString()));
- Exceptions::CreateAndThrowTypeError(
- location, AbstractType::Handle(zone), AbstractType::Handle(zone),
- Symbols::Empty(), bound_error_message);
+ String& bound_error_message =
+ String::Handle(zone, String::New(bound_error.ToErrorCString()));
+ Exceptions::CreateAndThrowTypeError(location, AbstractType::Handle(zone),
+ AbstractType::Handle(zone),
+ Symbols::Empty(), bound_error_message);
UNREACHABLE();
}
return Bool::Get(negate.value() ? !is_instance_of : is_instance_of).raw();
@@ -221,20 +220,19 @@
ASSERT(!type.IsMalformed());
ASSERT(!type.IsMalbounded());
Error& bound_error = Error::Handle(zone, Error::null());
- const bool is_instance_of = instance.IsInstanceOf(type,
- instantiator_type_arguments,
- &bound_error);
+ const bool is_instance_of =
+ instance.IsInstanceOf(type, instantiator_type_arguments, &bound_error);
if (!is_instance_of && !bound_error.IsNull()) {
// Throw a dynamic type error only if the instanceof test fails.
DartFrameIterator iterator;
StackFrame* caller_frame = iterator.NextFrame();
ASSERT(caller_frame != NULL);
const TokenPosition location = caller_frame->GetTokenPos();
- String& bound_error_message = String::Handle(
- zone, String::New(bound_error.ToErrorCString()));
- Exceptions::CreateAndThrowTypeError(
- location, AbstractType::Handle(zone), AbstractType::Handle(zone),
- Symbols::Empty(), bound_error_message);
+ String& bound_error_message =
+ String::Handle(zone, String::New(bound_error.ToErrorCString()));
+ Exceptions::CreateAndThrowTypeError(location, AbstractType::Handle(zone),
+ AbstractType::Handle(zone),
+ Symbols::Empty(), bound_error_message);
UNREACHABLE();
}
return Bool::Get(is_instance_of).raw();
@@ -314,9 +312,8 @@
if (instance.IsNull()) {
return instance.raw();
}
- const bool is_instance_of = instance.IsInstanceOf(type,
- instantiator_type_arguments,
- &bound_error);
+ const bool is_instance_of =
+ instance.IsInstanceOf(type, instantiator_type_arguments, &bound_error);
if (FLAG_trace_type_checks) {
const char* result_str = is_instance_of ? "true" : "false";
OS::Print("Object.as: result %s\n", result_str);
@@ -339,21 +336,21 @@
AbstractType::Handle(zone, instance.GetType());
if (!type.IsInstantiated()) {
// Instantiate type before reporting the error.
- type = type.InstantiateFrom(instantiator_type_arguments, NULL,
- NULL, NULL, Heap::kNew);
+ type = type.InstantiateFrom(instantiator_type_arguments, NULL, NULL, NULL,
+ Heap::kNew);
// Note that the instantiated type may be malformed.
}
if (bound_error.IsNull()) {
- Exceptions::CreateAndThrowTypeError(
- location, instance_type, type,
- Symbols::InTypeCast(), Object::null_string());
+ Exceptions::CreateAndThrowTypeError(location, instance_type, type,
+ Symbols::InTypeCast(),
+ Object::null_string());
} else {
ASSERT(isolate->type_checks());
const String& bound_error_message =
String::Handle(zone, String::New(bound_error.ToErrorCString()));
Exceptions::CreateAndThrowTypeError(
- location, instance_type, AbstractType::Handle(zone),
- Symbols::Empty(), bound_error_message);
+ location, instance_type, AbstractType::Handle(zone), Symbols::Empty(),
+ bound_error_message);
}
UNREACHABLE();
}
diff --git a/runtime/lib/regexp.cc b/runtime/lib/regexp.cc
index 921a101..7a50561 100644
--- a/runtime/lib/regexp.cc
+++ b/runtime/lib/regexp.cc
@@ -20,10 +20,10 @@
DEFINE_NATIVE_ENTRY(RegExp_factory, 4) {
ASSERT(TypeArguments::CheckedHandle(arguments->NativeArgAt(0)).IsNull());
GET_NON_NULL_NATIVE_ARGUMENT(String, pattern, arguments->NativeArgAt(1));
- GET_NON_NULL_NATIVE_ARGUMENT(
- Instance, handle_multi_line, arguments->NativeArgAt(2));
- GET_NON_NULL_NATIVE_ARGUMENT(
- Instance, handle_case_sensitive, arguments->NativeArgAt(3));
+ GET_NON_NULL_NATIVE_ARGUMENT(Instance, handle_multi_line,
+ arguments->NativeArgAt(2));
+ GET_NON_NULL_NATIVE_ARGUMENT(Instance, handle_case_sensitive,
+ arguments->NativeArgAt(3));
bool ignore_case = handle_case_sensitive.raw() != Bool::True().raw();
bool multi_line = handle_multi_line.raw() == Bool::True().raw();
@@ -36,10 +36,7 @@
}
// Create a RegExp object containing only the initial parameters.
- return RegExpEngine::CreateRegExp(thread,
- pattern,
- multi_line,
- ignore_case);
+ return RegExpEngine::CreateRegExp(thread, pattern, multi_line, ignore_case);
}
diff --git a/runtime/lib/simd128.cc b/runtime/lib/simd128.cc
index 4492555..f9520c3 100644
--- a/runtime/lib/simd128.cc
+++ b/runtime/lib/simd128.cc
@@ -13,8 +13,8 @@
static void ThrowMaskRangeException(int64_t m) {
if ((m < 0) || (m > 255)) {
- Exceptions::ThrowRangeError(
- "mask", Integer::Handle(Integer::New(m)), 0, 255);
+ Exceptions::ThrowRangeError("mask", Integer::Handle(Integer::New(m)), 0,
+ 255);
}
}
@@ -95,8 +95,7 @@
DEFINE_NATIVE_ENTRY(Float32x4_mul, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(Float32x4, self, arguments->NativeArgAt(0));
- GET_NON_NULL_NATIVE_ARGUMENT(Float32x4, other,
- arguments->NativeArgAt(1));
+ GET_NON_NULL_NATIVE_ARGUMENT(Float32x4, other, arguments->NativeArgAt(1));
float _x = self.x() * other.x();
float _y = self.y() * other.y();
float _z = self.z() * other.z();
@@ -277,7 +276,7 @@
GET_NON_NULL_NATIVE_ARGUMENT(Integer, mask, arguments->NativeArgAt(1));
int64_t m = mask.AsInt64Value();
ThrowMaskRangeException(m);
- float data[4] = { self.x(), self.y(), self.z(), self.w() };
+ float data[4] = {self.x(), self.y(), self.z(), self.w()};
float _x = data[m & 0x3];
float _y = data[(m >> 2) & 0x3];
float _z = data[(m >> 4) & 0x3];
@@ -292,8 +291,8 @@
GET_NON_NULL_NATIVE_ARGUMENT(Integer, mask, arguments->NativeArgAt(2));
int64_t m = mask.AsInt64Value();
ThrowMaskRangeException(m);
- float data[4] = { self.x(), self.y(), self.z(), self.w() };
- float other_data[4] = { other.x(), other.y(), other.z(), other.w() };
+ float data[4] = {self.x(), self.y(), self.z(), self.w()};
+ float other_data[4] = {other.x(), other.y(), other.z(), other.w()};
float _x = data[m & 0x3];
float _y = data[(m >> 2) & 0x3];
float _z = other_data[(m >> 4) & 0x3];
@@ -348,8 +347,7 @@
DEFINE_NATIVE_ENTRY(Float32x4_min, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(Float32x4, self, arguments->NativeArgAt(0));
- GET_NON_NULL_NATIVE_ARGUMENT(Float32x4, other,
- arguments->NativeArgAt(1));
+ GET_NON_NULL_NATIVE_ARGUMENT(Float32x4, other, arguments->NativeArgAt(1));
float _x = self.x() < other.x() ? self.x() : other.x();
float _y = self.y() < other.y() ? self.y() : other.y();
float _z = self.z() < other.z() ? self.z() : other.z();
@@ -360,8 +358,7 @@
DEFINE_NATIVE_ENTRY(Float32x4_max, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(Float32x4, self, arguments->NativeArgAt(0));
- GET_NON_NULL_NATIVE_ARGUMENT(Float32x4, other,
- arguments->NativeArgAt(1));
+ GET_NON_NULL_NATIVE_ARGUMENT(Float32x4, other, arguments->NativeArgAt(1));
float _x = self.x() > other.x() ? self.x() : other.x();
float _y = self.y() > other.y() ? self.y() : other.y();
float _z = self.z() > other.z() ? self.z() : other.z();
@@ -522,7 +519,7 @@
GET_NON_NULL_NATIVE_ARGUMENT(Integer, mask, arguments->NativeArgAt(1));
int64_t m = mask.AsInt64Value();
ThrowMaskRangeException(m);
- int32_t data[4] = { self.x(), self.y(), self.z(), self.w() };
+ int32_t data[4] = {self.x(), self.y(), self.z(), self.w()};
int32_t _x = data[m & 0x3];
int32_t _y = data[(m >> 2) & 0x3];
int32_t _z = data[(m >> 4) & 0x3];
@@ -537,8 +534,8 @@
GET_NON_NULL_NATIVE_ARGUMENT(Integer, mask, arguments->NativeArgAt(2));
int64_t m = mask.AsInt64Value();
ThrowMaskRangeException(m);
- int32_t data[4] = { self.x(), self.y(), self.z(), self.w() };
- int32_t zw_data[4] = { zw.x(), zw.y(), zw.z(), zw.w() };
+ int32_t data[4] = {self.x(), self.y(), self.z(), self.w()};
+ int32_t zw_data[4] = {zw.x(), zw.y(), zw.z(), zw.w()};
int32_t _x = data[m & 0x3];
int32_t _y = data[(m >> 2) & 0x3];
int32_t _z = zw_data[(m >> 4) & 0x3];
@@ -672,12 +669,8 @@
union float32_int32 {
float f;
int32_t u;
- float32_int32(float v) {
- f = v;
- }
- float32_int32(int32_t v) {
- u = v;
- }
+ float32_int32(float v) { f = v; }
+ float32_int32(int32_t v) { u = v; }
};
@@ -854,8 +847,7 @@
DEFINE_NATIVE_ENTRY(Float64x2_min, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(Float64x2, self, arguments->NativeArgAt(0));
- GET_NON_NULL_NATIVE_ARGUMENT(Float64x2, other,
- arguments->NativeArgAt(1));
+ GET_NON_NULL_NATIVE_ARGUMENT(Float64x2, other, arguments->NativeArgAt(1));
double _x = self.x() < other.x() ? self.x() : other.x();
double _y = self.y() < other.y() ? self.y() : other.y();
return Float64x2::New(_x, _y);
@@ -864,8 +856,7 @@
DEFINE_NATIVE_ENTRY(Float64x2_max, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(Float64x2, self, arguments->NativeArgAt(0));
- GET_NON_NULL_NATIVE_ARGUMENT(Float64x2, other,
- arguments->NativeArgAt(1));
+ GET_NON_NULL_NATIVE_ARGUMENT(Float64x2, other, arguments->NativeArgAt(1));
double _x = self.x() > other.x() ? self.x() : other.x();
double _y = self.y() > other.y() ? self.y() : other.y();
return Float64x2::New(_x, _y);
diff --git a/runtime/lib/stacktrace.cc b/runtime/lib/stacktrace.cc
index 12d6058..dcc4834 100644
--- a/runtime/lib/stacktrace.cc
+++ b/runtime/lib/stacktrace.cc
@@ -46,8 +46,8 @@
const Array& code_array = Array::Handle(Array::MakeArray(code_list));
const Array& pc_offset_array =
Array::Handle(Array::MakeArray(pc_offset_list));
- const Stacktrace& stacktrace = Stacktrace::Handle(
- Stacktrace::New(code_array, pc_offset_array));
+ const Stacktrace& stacktrace =
+ Stacktrace::Handle(Stacktrace::New(code_array, pc_offset_array));
return stacktrace;
}
diff --git a/runtime/lib/string.cc b/runtime/lib/string.cc
index d4008a3..8affbbd 100644
--- a/runtime/lib/string.cc
+++ b/runtime/lib/string.cc
@@ -91,8 +91,8 @@
DEFINE_NATIVE_ENTRY(StringBase_substringUnchecked, 3) {
- const String& receiver = String::CheckedHandle(zone,
- arguments->NativeArgAt(0));
+ const String& receiver =
+ String::CheckedHandle(zone, arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(Smi, start_obj, arguments->NativeArgAt(1));
GET_NON_NULL_NATIVE_ARGUMENT(Smi, end_obj, arguments->NativeArgAt(2));
@@ -102,10 +102,10 @@
}
-
// Return the bitwise-or of all characters in the slice from start to end.
static uint16_t CharacterLimit(const String& string,
- intptr_t start, intptr_t end) {
+ intptr_t start,
+ intptr_t end) {
ASSERT(string.IsTwoByteString() || string.IsExternalTwoByteString());
// Maybe do loop unrolling, and handle two uint16_t in a single uint32_t
// operation.
@@ -164,10 +164,9 @@
DEFINE_NATIVE_ENTRY(StringBase_joinReplaceAllResult, 4) {
- const String& base = String::CheckedHandle(zone,
- arguments->NativeArgAt(0));
- GET_NON_NULL_NATIVE_ARGUMENT(GrowableObjectArray,
- matches_growable, arguments->NativeArgAt(1));
+ const String& base = String::CheckedHandle(zone, arguments->NativeArgAt(0));
+ GET_NON_NULL_NATIVE_ARGUMENT(GrowableObjectArray, matches_growable,
+ arguments->NativeArgAt(1));
GET_NON_NULL_NATIVE_ARGUMENT(Smi, length_obj, arguments->NativeArgAt(2));
GET_NON_NULL_NATIVE_ARGUMENT(Bool, is_onebyte_obj, arguments->NativeArgAt(3));
@@ -219,12 +218,9 @@
}
}
if (slice_length > 0) {
- if (0 <= slice_start &&
- slice_start + slice_length <= base_length &&
+ if (0 <= slice_start && slice_start + slice_length <= base_length &&
write_index + slice_length <= length) {
- String::Copy(result, write_index,
- base, slice_start,
- slice_length);
+ String::Copy(result, write_index, base, slice_start, slice_length);
write_index += slice_length;
continue;
}
@@ -253,8 +249,8 @@
}
DEFINE_NATIVE_ENTRY(OneByteString_substringUnchecked, 3) {
- const String& receiver = String::CheckedHandle(zone,
- arguments->NativeArgAt(0));
+ const String& receiver =
+ String::CheckedHandle(zone, arguments->NativeArgAt(0));
ASSERT(receiver.IsOneByteString());
GET_NON_NULL_NATIVE_ARGUMENT(Smi, start_obj, arguments->NativeArgAt(1));
GET_NON_NULL_NATIVE_ARGUMENT(Smi, end_obj, arguments->NativeArgAt(2));
@@ -267,31 +263,26 @@
// This is high-performance code.
DEFINE_NATIVE_ENTRY(OneByteString_splitWithCharCode, 2) {
- const String& receiver = String::CheckedHandle(zone,
- arguments->NativeArgAt(0));
+ const String& receiver =
+ String::CheckedHandle(zone, arguments->NativeArgAt(0));
ASSERT(receiver.IsOneByteString());
GET_NON_NULL_NATIVE_ARGUMENT(Smi, smi_split_code, arguments->NativeArgAt(1));
const intptr_t len = receiver.Length();
const intptr_t split_code = smi_split_code.Value();
const GrowableObjectArray& result = GrowableObjectArray::Handle(
- zone,
- GrowableObjectArray::New(16, Heap::kNew));
+ zone, GrowableObjectArray::New(16, Heap::kNew));
String& str = String::Handle(zone);
intptr_t start = 0;
intptr_t i = 0;
for (; i < len; i++) {
if (split_code == OneByteString::CharAt(receiver, i)) {
- str = OneByteString::SubStringUnchecked(receiver,
- start,
- (i - start),
+ str = OneByteString::SubStringUnchecked(receiver, start, (i - start),
Heap::kNew);
result.Add(str);
start = i + 1;
}
}
- str = OneByteString::SubStringUnchecked(receiver,
- start,
- (i - start),
+ str = OneByteString::SubStringUnchecked(receiver, start, (i - start),
Heap::kNew);
result.Add(str);
return result.raw();
@@ -305,8 +296,7 @@
DEFINE_NATIVE_ENTRY(OneByteString_allocateFromOneByteList, 3) {
- Instance& list = Instance::CheckedHandle(zone,
- arguments->NativeArgAt(0));
+ Instance& list = Instance::CheckedHandle(zone, arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(Smi, start_obj, arguments->NativeArgAt(1));
GET_NON_NULL_NATIVE_ARGUMENT(Smi, end_obj, arguments->NativeArgAt(2));
@@ -409,8 +399,7 @@
DEFINE_NATIVE_ENTRY(TwoByteString_allocateFromTwoByteList, 3) {
- Instance& list = Instance::CheckedHandle(zone,
- arguments->NativeArgAt(0));
+ Instance& list = Instance::CheckedHandle(zone, arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(Smi, start_obj, arguments->NativeArgAt(1));
GET_NON_NULL_NATIVE_ARGUMENT(Smi, end_obj, arguments->NativeArgAt(2));
@@ -451,8 +440,8 @@
if (end > Smi::Value(TypedDataView::Length(list))) {
Exceptions::ThrowArgumentError(end_obj);
}
- const Instance& data_obj = Instance::Handle(zone,
- TypedDataView::Data(list));
+ const Instance& data_obj =
+ Instance::Handle(zone, TypedDataView::Data(list));
intptr_t data_offset = Smi::Value(TypedDataView::OffsetInBytes(list));
if (data_obj.IsTypedData()) {
const TypedData& array = TypedData::Cast(data_obj);
@@ -468,8 +457,8 @@
if (end > array.Length()) {
Exceptions::ThrowArgumentError(end_obj);
}
- const String& string = String::Handle(zone,
- TwoByteString::New(length, space));
+ const String& string =
+ String::Handle(zone, TwoByteString::New(length, space));
for (int i = 0; i < length; i++) {
intptr_t value =
Smi::Value(reinterpret_cast<RawSmi*>(array.At(start + i)));
@@ -481,8 +470,8 @@
if (end > array.Length()) {
Exceptions::ThrowArgumentError(end_obj);
}
- const String& string = String::Handle(zone,
- TwoByteString::New(length, space));
+ const String& string =
+ String::Handle(zone, TwoByteString::New(length, space));
for (int i = 0; i < length; i++) {
intptr_t value =
Smi::Value(reinterpret_cast<RawSmi*>(array.At(start + i)));
@@ -496,8 +485,8 @@
DEFINE_NATIVE_ENTRY(String_getHashCode, 1) {
- const String& receiver = String::CheckedHandle(zone,
- arguments->NativeArgAt(0));
+ const String& receiver =
+ String::CheckedHandle(zone, arguments->NativeArgAt(0));
intptr_t hash_val = receiver.Hash();
ASSERT(hash_val > 0);
ASSERT(Smi::IsValid(hash_val));
@@ -506,8 +495,8 @@
DEFINE_NATIVE_ENTRY(String_getLength, 1) {
- const String& receiver = String::CheckedHandle(zone,
- arguments->NativeArgAt(0));
+ const String& receiver =
+ String::CheckedHandle(zone, arguments->NativeArgAt(0));
return Smi::New(receiver.Length());
}
@@ -527,8 +516,8 @@
DEFINE_NATIVE_ENTRY(String_charAt, 2) {
- const String& receiver = String::CheckedHandle(zone,
- arguments->NativeArgAt(0));
+ const String& receiver =
+ String::CheckedHandle(zone, arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(Integer, index, arguments->NativeArgAt(1));
uint16_t value = StringValueAt(receiver, index);
return Symbols::FromCharCode(thread, static_cast<int32_t>(value));
@@ -537,8 +526,8 @@
// Returns the 16-bit UTF-16 code unit at the given index.
DEFINE_NATIVE_ENTRY(String_codeUnitAt, 2) {
- const String& receiver = String::CheckedHandle(zone,
- arguments->NativeArgAt(0));
+ const String& receiver =
+ String::CheckedHandle(zone, arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(Integer, index, arguments->NativeArgAt(1));
uint16_t value = StringValueAt(receiver, index);
return Smi::New(static_cast<intptr_t>(value));
@@ -546,24 +535,24 @@
DEFINE_NATIVE_ENTRY(String_concat, 2) {
- const String& receiver = String::CheckedHandle(zone,
- arguments->NativeArgAt(0));
+ const String& receiver =
+ String::CheckedHandle(zone, arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(String, b, arguments->NativeArgAt(1));
return String::Concat(receiver, b);
}
DEFINE_NATIVE_ENTRY(String_toLowerCase, 1) {
- const String& receiver = String::CheckedHandle(zone,
- arguments->NativeArgAt(0));
+ const String& receiver =
+ String::CheckedHandle(zone, arguments->NativeArgAt(0));
ASSERT(!receiver.IsNull());
return String::ToLowerCase(receiver);
}
DEFINE_NATIVE_ENTRY(String_toUpperCase, 1) {
- const String& receiver = String::CheckedHandle(zone,
- arguments->NativeArgAt(0));
+ const String& receiver =
+ String::CheckedHandle(zone, arguments->NativeArgAt(0));
ASSERT(!receiver.IsNull());
return String::ToUpperCase(receiver);
}
@@ -586,7 +575,7 @@
} else if (argument.IsGrowableObjectArray()) {
const GrowableObjectArray& g_array = GrowableObjectArray::Cast(argument);
strings = g_array.data();
- length = g_array.Length();
+ length = g_array.Length();
} else {
Exceptions::ThrowArgumentError(argument);
}
@@ -614,9 +603,10 @@
if (length_value < 0 || length_value > array_length) {
Exceptions::ThrowRangeError("length", length, 0, array_length);
}
- const String& result = isLatin1.value()
- ? String::Handle(OneByteString::New(length_value, Heap::kNew))
- : String::Handle(TwoByteString::New(length_value, Heap::kNew));
+ const String& result =
+ isLatin1.value()
+ ? String::Handle(OneByteString::New(length_value, Heap::kNew))
+ : String::Handle(TwoByteString::New(length_value, Heap::kNew));
NoSafepointScope no_safepoint;
uint16_t* data_position = reinterpret_cast<uint16_t*>(codeUnits.DataAddr(0));
diff --git a/runtime/lib/timeline.cc b/runtime/lib/timeline.cc
index 300d6e3..18b89e9 100644
--- a/runtime/lib/timeline.cc
+++ b/runtime/lib/timeline.cc
@@ -85,32 +85,26 @@
// Convert phase to a C string and perform a sanity check.
const char* phase_string = phase.ToCString();
ASSERT(phase_string != NULL);
- ASSERT((phase_string[0] == 'n') ||
- (phase_string[0] == 'b') ||
+ ASSERT((phase_string[0] == 'n') || (phase_string[0] == 'b') ||
(phase_string[0] == 'e'));
ASSERT(phase_string[1] == '\0');
- char* json = OS::SCreate(zone,
- "{\"name\":\"%s\",\"cat\":\"%s\",\"tid\":%" Pd64 ",\"pid\":%" Pd64 ","
- "\"ts\":%" Pd64 ",\"ph\":\"%s\",\"id\":%" Pd64 ", \"args\":%s}",
- name.ToCString(),
- category.ToCString(),
- tid,
- pid,
- start.AsInt64Value(),
- phase_string,
- id.AsInt64Value(),
- args.ToCString());
+ char* json = OS::SCreate(
+ zone, "{\"name\":\"%s\",\"cat\":\"%s\",\"tid\":%" Pd64 ",\"pid\":%" Pd64
+ ","
+ "\"ts\":%" Pd64 ",\"ph\":\"%s\",\"id\":%" Pd64 ", \"args\":%s}",
+ name.ToCString(), category.ToCString(), tid, pid, start.AsInt64Value(),
+ phase_string, id.AsInt64Value(), args.ToCString());
switch (phase_string[0]) {
case 'n':
event->AsyncInstant("", id.AsInt64Value(), start.AsInt64Value());
- break;
+ break;
case 'b':
event->AsyncBegin("", id.AsInt64Value(), start.AsInt64Value());
- break;
+ break;
case 'e':
event->AsyncEnd("", id.AsInt64Value(), start.AsInt64Value());
- break;
+ break;
default:
UNREACHABLE();
}
@@ -156,36 +150,25 @@
char* json = NULL;
if ((start_cpu.AsInt64Value() != -1) && (end_cpu != -1)) {
- json = OS::SCreate(zone,
- "{\"name\":\"%s\",\"cat\":\"%s\",\"tid\":%" Pd64 ",\"pid\":%" Pd64 ","
- "\"ts\":%" Pd64 ",\"ph\":\"X\",\"dur\":%" Pd64 ","
- "\"tdur\":%" Pd64 ",\"args\":%s}",
- name.ToCString(),
- category.ToCString(),
- tid,
- pid,
- start.AsInt64Value(),
- duration,
- duration_cpu,
- args.ToCString());
+ json = OS::SCreate(
+ zone, "{\"name\":\"%s\",\"cat\":\"%s\",\"tid\":%" Pd64 ",\"pid\":%" Pd64
+ ","
+ "\"ts\":%" Pd64 ",\"ph\":\"X\",\"dur\":%" Pd64
+ ","
+ "\"tdur\":%" Pd64 ",\"args\":%s}",
+ name.ToCString(), category.ToCString(), tid, pid, start.AsInt64Value(),
+ duration, duration_cpu, args.ToCString());
} else {
- json = OS::SCreate(zone,
- "{\"name\":\"%s\",\"cat\":\"%s\",\"tid\":%" Pd64 ",\"pid\":%" Pd64 ","
- "\"ts\":%" Pd64 ",\"ph\":\"X\",\"dur\":%" Pd64 ",\"args\":%s}",
- name.ToCString(),
- category.ToCString(),
- tid,
- pid,
- start.AsInt64Value(),
- duration,
- args.ToCString());
+ json = OS::SCreate(
+ zone, "{\"name\":\"%s\",\"cat\":\"%s\",\"tid\":%" Pd64 ",\"pid\":%" Pd64
+ ","
+ "\"ts\":%" Pd64 ",\"ph\":\"X\",\"dur\":%" Pd64 ",\"args\":%s}",
+ name.ToCString(), category.ToCString(), tid, pid, start.AsInt64Value(),
+ duration, args.ToCString());
}
ASSERT(json != NULL);
- event->Duration("",
- start.AsInt64Value(),
- end,
- start_cpu.AsInt64Value(),
+ event->Duration("", start.AsInt64Value(), end, start_cpu.AsInt64Value(),
end_cpu);
// json was allocated in the zone and a copy will be stored in event.
event->CompleteWithPreSerializedJSON(json);
@@ -220,14 +203,11 @@
ASSERT(os_thread != NULL);
int64_t tid = OSThread::ThreadIdToIntPtr(os_thread->trace_id());
- char* json = OS::SCreate(zone,
- "{\"name\":\"%s\",\"cat\":\"%s\",\"tid\":%" Pd64 ",\"pid\":%" Pd64 ","
- "\"ts\":%" Pd64 ",\"ph\":\"I\",\"args\":%s}",
- name.ToCString(),
- category.ToCString(),
- tid,
- pid,
- start.AsInt64Value(),
+ char* json = OS::SCreate(
+ zone, "{\"name\":\"%s\",\"cat\":\"%s\",\"tid\":%" Pd64 ",\"pid\":%" Pd64
+ ","
+ "\"ts\":%" Pd64 ",\"ph\":\"I\",\"args\":%s}",
+ name.ToCString(), category.ToCString(), tid, pid, start.AsInt64Value(),
args.ToCString());
event->Instant("", start.AsInt64Value());
diff --git a/runtime/lib/typed_data.cc b/runtime/lib/typed_data.cc
index 4130e60..986c035 100644
--- a/runtime/lib/typed_data.cc
+++ b/runtime/lib/typed_data.cc
@@ -22,10 +22,9 @@
if (!Utils::RangeCheck(offset_in_bytes, access_size, length_in_bytes)) {
const intptr_t index =
(offset_in_bytes + access_size) / element_size_in_bytes;
- const intptr_t length =
- length_in_bytes / element_size_in_bytes;
- Exceptions::ThrowRangeError(
- "index", Integer::Handle(Integer::New(index)), 0, length);
+ const intptr_t length = length_in_bytes / element_size_in_bytes;
+ Exceptions::ThrowRangeError("index", Integer::Handle(Integer::New(index)),
+ 0, length);
}
}
@@ -34,8 +33,7 @@
static void LengthCheck(intptr_t len, intptr_t max) {
if (len < 0 || len > max) {
const String& error = String::Handle(String::NewFormatted(
- "Length (%" Pd ") of object must be in range [0..%" Pd "]",
- len, max));
+ "Length (%" Pd ") of object must be in range [0..%" Pd "]", len, max));
Exceptions::ThrowArgumentError(error);
}
}
@@ -44,8 +42,8 @@
DEFINE_NATIVE_ENTRY(TypedData_length, 1) {
GET_NON_NULL_NATIVE_ARGUMENT(Instance, instance, arguments->NativeArgAt(0));
if (instance.IsTypedData()) {
- const TypedData& array = TypedData::Cast(instance);
- return Smi::New(array.Length());
+ const TypedData& array = TypedData::Cast(instance);
+ return Smi::New(array.Length());
}
if (instance.IsExternalTypedData()) {
const ExternalTypedData& array = ExternalTypedData::Cast(instance);
@@ -59,8 +57,10 @@
template <typename DstType, typename SrcType>
-static RawBool* CopyData(const Instance& dst, const Instance& src,
- const Smi& dst_start, const Smi& src_start,
+static RawBool* CopyData(const Instance& dst,
+ const Instance& src,
+ const Smi& dst_start,
+ const Smi& src_start,
const Smi& length,
bool clamped) {
const DstType& dst_array = DstType::Cast(dst);
@@ -68,18 +68,17 @@
const intptr_t dst_offset_in_bytes = dst_start.Value();
const intptr_t src_offset_in_bytes = src_start.Value();
const intptr_t length_in_bytes = length.Value();
- ASSERT(Utils::RangeCheck(
- src_offset_in_bytes, length_in_bytes, src_array.LengthInBytes()));
- ASSERT(Utils::RangeCheck(
- dst_offset_in_bytes, length_in_bytes, dst_array.LengthInBytes()));
+ ASSERT(Utils::RangeCheck(src_offset_in_bytes, length_in_bytes,
+ src_array.LengthInBytes()));
+ ASSERT(Utils::RangeCheck(dst_offset_in_bytes, length_in_bytes,
+ dst_array.LengthInBytes()));
if (clamped) {
TypedData::ClampedCopy<DstType, SrcType>(dst_array, dst_offset_in_bytes,
src_array, src_offset_in_bytes,
length_in_bytes);
} else {
- TypedData::Copy<DstType, SrcType>(dst_array, dst_offset_in_bytes,
- src_array, src_offset_in_bytes,
- length_in_bytes);
+ TypedData::Copy<DstType, SrcType>(dst_array, dst_offset_in_bytes, src_array,
+ src_offset_in_bytes, length_in_bytes);
}
return Bool::True().raw();
}
@@ -132,8 +131,8 @@
const bool needs_clamping = IsClamped(to_cid) && !IsUint8(from_cid);
if (dst.IsTypedData()) {
if (src.IsTypedData()) {
- return CopyData<TypedData, TypedData>(
- dst, src, dst_start, src_start, length, needs_clamping);
+ return CopyData<TypedData, TypedData>(dst, src, dst_start, src_start,
+ length, needs_clamping);
} else if (src.IsExternalTypedData()) {
return CopyData<TypedData, ExternalTypedData>(
dst, src, dst_start, src_start, length, needs_clamping);
@@ -158,83 +157,79 @@
// on whether the underlying architecture is 32-bit or 64-bit.
// Argument 0 is type arguments and is ignored.
#define TYPED_DATA_NEW(name) \
-DEFINE_NATIVE_ENTRY(TypedData_##name##_new, 2) { \
- GET_NON_NULL_NATIVE_ARGUMENT(Smi, length, arguments->NativeArgAt(1)); \
- intptr_t cid = kTypedData##name##Cid; \
- intptr_t len = length.Value(); \
- intptr_t max = TypedData::MaxElements(cid); \
- LengthCheck(len, max); \
- return TypedData::New(cid, len); \
-} \
+ DEFINE_NATIVE_ENTRY(TypedData_##name##_new, 2) { \
+ GET_NON_NULL_NATIVE_ARGUMENT(Smi, length, arguments->NativeArgAt(1)); \
+ intptr_t cid = kTypedData##name##Cid; \
+ intptr_t len = length.Value(); \
+ intptr_t max = TypedData::MaxElements(cid); \
+ LengthCheck(len, max); \
+ return TypedData::New(cid, len); \
+ }
-#define TYPED_DATA_NEW_NATIVE(name) \
- TYPED_DATA_NEW(name) \
+#define TYPED_DATA_NEW_NATIVE(name) TYPED_DATA_NEW(name)
CLASS_LIST_TYPED_DATA(TYPED_DATA_NEW_NATIVE)
#define TYPED_DATA_GETTER(getter, object, ctor, access_size) \
-DEFINE_NATIVE_ENTRY(TypedData_##getter, 2) { \
- GET_NON_NULL_NATIVE_ARGUMENT(Instance, instance, arguments->NativeArgAt(0)); \
- GET_NON_NULL_NATIVE_ARGUMENT(Smi, offsetInBytes, arguments->NativeArgAt(1)); \
- if (instance.IsTypedData()) { \
- const TypedData& array = TypedData::Cast(instance); \
- RangeCheck(offsetInBytes.Value(), access_size, \
- array.LengthInBytes(), access_size); \
- return object::ctor(array.getter(offsetInBytes.Value())); \
- } \
- if (instance.IsExternalTypedData()) { \
- const ExternalTypedData& array = ExternalTypedData::Cast(instance); \
- RangeCheck(offsetInBytes.Value(), access_size, \
- array.LengthInBytes(), access_size); \
- return object::ctor(array.getter(offsetInBytes.Value())); \
- } \
- const String& error = String::Handle(String::NewFormatted( \
- "Expected a TypedData object but found %s", instance.ToCString())); \
- Exceptions::ThrowArgumentError(error); \
- return object::null(); \
-} \
-
-
-#define TYPED_DATA_SETTER(setter, \
- object, \
- get_object_value, \
- access_size, \
- access_type) \
-DEFINE_NATIVE_ENTRY(TypedData_##setter, 3) { \
- GET_NON_NULL_NATIVE_ARGUMENT(Instance, instance, arguments->NativeArgAt(0)); \
- GET_NON_NULL_NATIVE_ARGUMENT(Smi, offsetInBytes, arguments->NativeArgAt(1)); \
- GET_NON_NULL_NATIVE_ARGUMENT(object, value, arguments->NativeArgAt(2)); \
- if (instance.IsTypedData()) { \
- const TypedData& array = TypedData::Cast(instance); \
- RangeCheck(offsetInBytes.Value(), access_size, \
- array.LengthInBytes(), access_size); \
- array.setter(offsetInBytes.Value(), \
- static_cast<access_type>(value.get_object_value())); \
- } else if (instance.IsExternalTypedData()) { \
- const ExternalTypedData& array = ExternalTypedData::Cast(instance); \
- RangeCheck(offsetInBytes.Value(), access_size, \
- array.LengthInBytes(), access_size); \
- array.setter(offsetInBytes.Value(), \
- static_cast<access_type>(value.get_object_value())); \
- } else { \
+ DEFINE_NATIVE_ENTRY(TypedData_##getter, 2) { \
+ GET_NON_NULL_NATIVE_ARGUMENT(Instance, instance, \
+ arguments->NativeArgAt(0)); \
+ GET_NON_NULL_NATIVE_ARGUMENT(Smi, offsetInBytes, \
+ arguments->NativeArgAt(1)); \
+ if (instance.IsTypedData()) { \
+ const TypedData& array = TypedData::Cast(instance); \
+ RangeCheck(offsetInBytes.Value(), access_size, array.LengthInBytes(), \
+ access_size); \
+ return object::ctor(array.getter(offsetInBytes.Value())); \
+ } \
+ if (instance.IsExternalTypedData()) { \
+ const ExternalTypedData& array = ExternalTypedData::Cast(instance); \
+ RangeCheck(offsetInBytes.Value(), access_size, array.LengthInBytes(), \
+ access_size); \
+ return object::ctor(array.getter(offsetInBytes.Value())); \
+ } \
const String& error = String::Handle(String::NewFormatted( \
"Expected a TypedData object but found %s", instance.ToCString())); \
Exceptions::ThrowArgumentError(error); \
- } \
- return Object::null(); \
-}
+ return object::null(); \
+ }
-#define TYPED_DATA_NATIVES(type_name, \
- object, \
- ctor, \
- get_object_value, \
- access_size, \
- access_type) \
+
+#define TYPED_DATA_SETTER(setter, object, get_object_value, access_size, \
+ access_type) \
+ DEFINE_NATIVE_ENTRY(TypedData_##setter, 3) { \
+ GET_NON_NULL_NATIVE_ARGUMENT(Instance, instance, \
+ arguments->NativeArgAt(0)); \
+ GET_NON_NULL_NATIVE_ARGUMENT(Smi, offsetInBytes, \
+ arguments->NativeArgAt(1)); \
+ GET_NON_NULL_NATIVE_ARGUMENT(object, value, arguments->NativeArgAt(2)); \
+ if (instance.IsTypedData()) { \
+ const TypedData& array = TypedData::Cast(instance); \
+ RangeCheck(offsetInBytes.Value(), access_size, array.LengthInBytes(), \
+ access_size); \
+ array.setter(offsetInBytes.Value(), \
+ static_cast<access_type>(value.get_object_value())); \
+ } else if (instance.IsExternalTypedData()) { \
+ const ExternalTypedData& array = ExternalTypedData::Cast(instance); \
+ RangeCheck(offsetInBytes.Value(), access_size, array.LengthInBytes(), \
+ access_size); \
+ array.setter(offsetInBytes.Value(), \
+ static_cast<access_type>(value.get_object_value())); \
+ } else { \
+ const String& error = String::Handle(String::NewFormatted( \
+ "Expected a TypedData object but found %s", instance.ToCString())); \
+ Exceptions::ThrowArgumentError(error); \
+ } \
+ return Object::null(); \
+ }
+
+#define TYPED_DATA_NATIVES(type_name, object, ctor, get_object_value, \
+ access_size, access_type) \
TYPED_DATA_GETTER(Get##type_name, object, ctor, access_size) \
- TYPED_DATA_SETTER(Set##type_name, object, \
- get_object_value, access_size, access_type) \
+ TYPED_DATA_SETTER(Set##type_name, object, get_object_value, access_size, \
+ access_type)
TYPED_DATA_NATIVES(Int8, Integer, New, AsTruncatedUint32Value, 1, int8_t)
TYPED_DATA_NATIVES(Uint8, Integer, New, AsTruncatedUint32Value, 1, uint8_t)
@@ -243,11 +238,15 @@
TYPED_DATA_NATIVES(Int32, Integer, New, AsTruncatedUint32Value, 4, int32_t)
TYPED_DATA_NATIVES(Uint32, Integer, New, AsTruncatedUint32Value, 4, uint32_t)
TYPED_DATA_NATIVES(Int64, Integer, New, AsTruncatedInt64Value, 8, int64_t)
-TYPED_DATA_NATIVES(
- Uint64, Integer, NewFromUint64, AsTruncatedInt64Value, 8, uint64_t)
+TYPED_DATA_NATIVES(Uint64,
+ Integer,
+ NewFromUint64,
+ AsTruncatedInt64Value,
+ 8,
+ uint64_t)
TYPED_DATA_NATIVES(Float32, Double, New, value, 4, float)
TYPED_DATA_NATIVES(Float64, Double, New, value, 8, double)
-TYPED_DATA_NATIVES(Float32x4, Float32x4, New, value, 16, simd128_value_t)
+TYPED_DATA_NATIVES(Float32x4, Float32x4, New, value, 16, simd128_value_t)
TYPED_DATA_NATIVES(Int32x4, Int32x4, New, value, 16, simd128_value_t)
TYPED_DATA_NATIVES(Float64x2, Float64x2, New, value, 16, simd128_value_t)
@@ -344,11 +343,11 @@
GET_NON_NULL_NATIVE_ARGUMENT(Bool, little_endian, arguments->NativeArgAt(1));
float value = host_value.value();
if (little_endian.value()) {
- value = bit_cast<float>(
- Utils::HostToLittleEndian32(bit_cast<uint32_t>(value)));
+ value =
+ bit_cast<float>(Utils::HostToLittleEndian32(bit_cast<uint32_t>(value)));
} else {
- value = bit_cast<float>(
- Utils::HostToBigEndian32(bit_cast<uint32_t>(value)));
+ value =
+ bit_cast<float>(Utils::HostToBigEndian32(bit_cast<uint32_t>(value)));
}
return Double::New(value);
}
@@ -362,8 +361,8 @@
value = bit_cast<double>(
Utils::HostToLittleEndian64(bit_cast<uint64_t>(value)));
} else {
- value = bit_cast<double>(
- Utils::HostToBigEndian64(bit_cast<uint64_t>(value)));
+ value =
+ bit_cast<double>(Utils::HostToBigEndian64(bit_cast<uint64_t>(value)));
}
return Double::New(value);
}
diff --git a/runtime/lib/vmservice.cc b/runtime/lib/vmservice.cc
index b4a8b14..6e39021 100644
--- a/runtime/lib/vmservice.cc
+++ b/runtime/lib/vmservice.cc
@@ -68,12 +68,11 @@
args.SetAt(0, port_int);
args.SetAt(1, send_port);
args.SetAt(2, name);
- const Object& r = Object::Handle(
- DartEntry::InvokeFunction(register_function_, args));
+ const Object& r =
+ Object::Handle(DartEntry::InvokeFunction(register_function_, args));
if (FLAG_trace_service) {
OS::Print("vm-service: Isolate %s %" Pd64 " registered.\n",
- name.ToCString(),
- port_id);
+ name.ToCString(), port_id);
}
ASSERT(!r.IsError());
}
@@ -92,8 +91,8 @@
GET_NON_NULL_NATIVE_ARGUMENT(Array, message, arguments->NativeArgAt(1));
// Set the type of the OOB message.
- message.SetAt(0, Smi::Handle(thread->zone(),
- Smi::New(Message::kServiceOOBMsg)));
+ message.SetAt(0,
+ Smi::Handle(thread->zone(), Smi::New(Message::kServiceOOBMsg)));
// Serialize message.
uint8_t* data = NULL;
@@ -102,8 +101,7 @@
// TODO(turnidge): Throw an exception when the return value is false?
bool result = PortMap::PostMessage(
- new Message(sp.Id(), data, writer.BytesWritten(),
- Message::kOOBPriority));
+ new Message(sp.Id(), data, writer.BytesWritten(), Message::kOOBPriority));
return Bool::Get(result).raw();
}
@@ -223,21 +221,13 @@
}
}
- char* NextFilename() {
- return filenames_.RemoveLast();
- }
+ char* NextFilename() { return filenames_.RemoveLast(); }
- uint8_t* NextContent() {
- return contents_.RemoveLast();
- }
+ uint8_t* NextContent() { return contents_.RemoveLast(); }
- intptr_t NextContentLength() {
- return content_lengths_.RemoveLast();
- }
+ intptr_t NextContentLength() { return content_lengths_.RemoveLast(); }
- bool HasMore() const {
- return filenames_.length() > 0;
- }
+ bool HasMore() const { return filenames_.length() > 0; }
intptr_t Length() const { return filenames_.length(); }
@@ -266,9 +256,7 @@
kTarXglType = 'g',
};
- bool HasNext() const {
- return !EndOfArchive();
- }
+ bool HasNext() const { return !EndOfArchive(); }
bool Next(char** filename, uint8_t** data, intptr_t* data_length) {
intptr_t startOfBlock = rs_.Position();
@@ -404,8 +392,8 @@
Dart_TypedData_Type typ;
void* bytes;
intptr_t length;
- Dart_Handle err = Dart_TypedDataAcquireData(
- data_handle, &typ, &bytes, &length);
+ Dart_Handle err =
+ Dart_TypedDataAcquireData(data_handle, &typ, &bytes, &length);
ASSERT(!Dart_IsError(err));
TarArchive archive(reinterpret_cast<uint8_t*>(bytes), length);
@@ -426,17 +414,15 @@
intptr_t contents_length = archive.NextContentLength();
Dart_Handle dart_filename = Dart_NewExternalLatin1String(
- reinterpret_cast<uint8_t*>(filename),
- strlen(filename),
- filename,
+ reinterpret_cast<uint8_t*>(filename), strlen(filename), filename,
FilenameFinalizer);
ASSERT(!Dart_IsError(dart_filename));
Dart_Handle dart_contents = Dart_NewExternalTypedData(
Dart_TypedData_kUint8, contents, contents_length);
ASSERT(!Dart_IsError(dart_contents));
- Dart_NewWeakPersistentHandle(
- dart_contents, contents, contents_length, ContentsFinalizer);
+ Dart_NewWeakPersistentHandle(dart_contents, contents, contents_length,
+ ContentsFinalizer);
Dart_ListSetAt(result_list, idx, dart_filename);
Dart_ListSetAt(result_list, (idx + 1), dart_contents);
@@ -449,7 +435,6 @@
}
-
DEFINE_NATIVE_ENTRY(VMService_spawnUriNotify, 2) {
#ifndef PRODUCT
if (!FLAG_support_service) {
@@ -469,8 +454,8 @@
// There is no isolate at the control port anymore. Must have
// died already.
ServiceEvent spawn_event(NULL, ServiceEvent::kIsolateSpawn);
- const String& error = String::Handle(String::New(
- "spawned isolate exited before notification completed"));
+ const String& error = String::Handle(
+ String::New("spawned isolate exited before notification completed"));
spawn_event.set_spawn_token(&token);
spawn_event.set_spawn_error(&error);
Service::HandleEvent(&spawn_event);
diff --git a/runtime/lib/weak_property.cc b/runtime/lib/weak_property.cc
index 80da580..88b9bf8 100644
--- a/runtime/lib/weak_property.cc
+++ b/runtime/lib/weak_property.cc
@@ -21,22 +21,22 @@
DEFINE_NATIVE_ENTRY(WeakProperty_getKey, 1) {
- GET_NON_NULL_NATIVE_ARGUMENT(
- WeakProperty, weak_property, arguments->NativeArgAt(0));
+ GET_NON_NULL_NATIVE_ARGUMENT(WeakProperty, weak_property,
+ arguments->NativeArgAt(0));
return weak_property.key();
}
DEFINE_NATIVE_ENTRY(WeakProperty_getValue, 1) {
- GET_NON_NULL_NATIVE_ARGUMENT(
- WeakProperty, weak_property, arguments->NativeArgAt(0));
+ GET_NON_NULL_NATIVE_ARGUMENT(WeakProperty, weak_property,
+ arguments->NativeArgAt(0));
return weak_property.value();
}
DEFINE_NATIVE_ENTRY(WeakProperty_setValue, 2) {
- GET_NON_NULL_NATIVE_ARGUMENT(
- WeakProperty, weak_property, arguments->NativeArgAt(0));
+ GET_NON_NULL_NATIVE_ARGUMENT(WeakProperty, weak_property,
+ arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(Instance, value, arguments->NativeArgAt(1));
weak_property.set_value(value);
return Object::null();
diff --git a/runtime/observatory/lib/src/elements/img/chromium_icon.png b/runtime/observatory/lib/src/elements/img/chromium_icon.png
index e6b0d45..a467bca 100644
--- a/runtime/observatory/lib/src/elements/img/chromium_icon.png
+++ b/runtime/observatory/lib/src/elements/img/chromium_icon.png
Binary files differ
diff --git a/runtime/observatory/lib/src/elements/img/dart_icon.png b/runtime/observatory/lib/src/elements/img/dart_icon.png
index 4772285..6341f65 100644
--- a/runtime/observatory/lib/src/elements/img/dart_icon.png
+++ b/runtime/observatory/lib/src/elements/img/dart_icon.png
Binary files differ
diff --git a/runtime/observatory/lib/src/elements/img/isolate_icon.png b/runtime/observatory/lib/src/elements/img/isolate_icon.png
index 57a5157..a739a54 100644
--- a/runtime/observatory/lib/src/elements/img/isolate_icon.png
+++ b/runtime/observatory/lib/src/elements/img/isolate_icon.png
Binary files differ
diff --git a/runtime/observatory/lib/src/elements/library_view.dart b/runtime/observatory/lib/src/elements/library_view.dart
index 2265d1b..165ffc8 100644
--- a/runtime/observatory/lib/src/elements/library_view.dart
+++ b/runtime/observatory/lib/src/elements/library_view.dart
@@ -156,7 +156,7 @@
new DivElement()
..classes = ['content-centered-big']
..children = [
- new HeadingElement.h2()..text = 'ICData',
+ new HeadingElement.h2()..text = 'Library',
new HRElement(),
new ObjectCommonElement(_isolate, _library, _retainedSizes,
_reachableSizes, _references, _retainingPaths, _instances,
diff --git a/runtime/observatory/tests/service/auth_token_test.dart b/runtime/observatory/tests/service/auth_token_test.dart
new file mode 100644
index 0000000..ce75e4f
--- /dev/null
+++ b/runtime/observatory/tests/service/auth_token_test.dart
@@ -0,0 +1,39 @@
+// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+// VMOptions=--error_on_bad_type --error_on_bad_override
+
+import 'dart:async';
+import 'dart:developer';
+import 'package:observatory/service_io.dart';
+import 'package:unittest/unittest.dart';
+import 'test_helper.dart';
+
+Future<Null> testeeBefore() async {
+ print('testee before');
+ print(await Service.getInfo());
+ // Start the web server.
+ ServiceProtocolInfo info = await Service.controlWebServer(enable: true);
+ expect(info.serverUri, isNotNull);
+ // Ensure that we have the auth token in the path segments.
+ expect(info.serverUri.pathSegments.length, greaterThan(1));
+ // Sanity check the length of the auth token.
+ expect(info.serverUri.pathSegments[0].length, greaterThan(8));
+}
+
+var tests = [
+(Isolate isolate) async {
+ await isolate.reload();
+ // Just getting here means that the testee enabled the service protocol
+ // web server.
+ expect(true, true);
+}
+];
+
+main(args) => runIsolateTests(args,
+ tests,
+ testeeBefore: testeeBefore,
+ // the testee is responsible for starting the
+ // web server.
+ testeeControlsServer: true,
+ useAuthToken: true);
diff --git a/runtime/observatory/tests/service/service.status b/runtime/observatory/tests/service/service.status
index fa58842..6810137 100644
--- a/runtime/observatory/tests/service/service.status
+++ b/runtime/observatory/tests/service/service.status
@@ -59,8 +59,6 @@
get_allocation_samples_test: RuntimeError # Profiling unimplemented.
get_cpu_profile_timeline_rpc_test: RuntimeError # Profiling unimplemented.
implicit_getter_setter_test: RuntimeError # Field guards unimplemented.
-debugger_location_second_test: Skip # Issue #27746
-debugger_location_test: Skip # Issue #27746
[ $hot_reload || $hot_reload_rollback ]
# Skip all service tests because random reloads interfere.
diff --git a/runtime/observatory/tests/service/test_helper.dart b/runtime/observatory/tests/service/test_helper.dart
index b1bf590..9e8caa8 100644
--- a/runtime/observatory/tests/service/test_helper.dart
+++ b/runtime/observatory/tests/service/test_helper.dart
@@ -92,13 +92,15 @@
bool pause_on_unhandled_exceptions,
bool trace_service,
bool trace_compiler,
- bool testeeControlsServer) {
+ bool testeeControlsServer,
+ bool useAuthToken) {
assert(pause_on_start != null);
assert(pause_on_exit != null);
assert(pause_on_unhandled_exceptions != null);
assert(trace_service != null);
assert(trace_compiler != null);
assert(testeeControlsServer != null);
+ assert(useAuthToken != null);
if (_shouldLaunchSkyShell()) {
return _spawnSkyProcess(pause_on_start,
@@ -113,7 +115,8 @@
pause_on_unhandled_exceptions,
trace_service,
trace_compiler,
- testeeControlsServer);
+ testeeControlsServer,
+ useAuthToken);
}
}
@@ -122,7 +125,8 @@
bool pause_on_unhandled_exceptions,
bool trace_service,
bool trace_compiler,
- bool testeeControlsServer) {
+ bool testeeControlsServer,
+ bool useAuthToken) {
assert(!_shouldLaunchSkyShell());
String dartExecutable = Platform.executable;
@@ -151,7 +155,12 @@
}
fullArgs.addAll(args);
- return _spawnCommon(dartExecutable, fullArgs);
+ return _spawnCommon(
+ dartExecutable,
+ fullArgs,
+ <String, String>{
+ 'DART_SERVICE_USE_AUTH': '$useAuthToken'
+ });
}
Future<Process> _spawnSkyProcess(bool pause_on_start,
@@ -193,13 +202,20 @@
fullArgs.add('--dart-flags=${dartFlags.join(' ')}');
fullArgs.addAll(args);
- return _spawnCommon(dartExecutable, fullArgs);
+ return _spawnCommon(dartExecutable, fullArgs, <String, String>{});
}
- Future<Process> _spawnCommon(String executable, List<String> arguments) {
+ Future<Process> _spawnCommon(String executable,
+ List<String> arguments,
+ Map<String, String> dartEnvironment) {
var environment = _TESTEE_SPAWN_ENV;
var bashEnvironment = new StringBuffer();
environment.forEach((k, v) => bashEnvironment.write("$k=$v "));
+ if (dartEnvironment != null) {
+ dartEnvironment.forEach((k, v) {
+ arguments.insert(0, '-D$k=$v');
+ });
+ }
print('** Launching $bashEnvironment$executable ${arguments.join(' ')}');
return Process.start(executable, arguments, environment: environment);
}
@@ -209,13 +225,15 @@
bool pause_on_unhandled_exceptions,
bool trace_service,
bool trace_compiler,
- bool testeeControlsServer) {
+ bool testeeControlsServer,
+ bool useAuthToken) {
return _spawnProcess(pause_on_start,
pause_on_exit,
pause_on_unhandled_exceptions,
trace_service,
trace_compiler,
- testeeControlsServer).then((p) {
+ testeeControlsServer,
+ useAuthToken).then((p) {
Completer<Uri> completer = new Completer<Uri>();
process = p;
Uri uri;
@@ -278,12 +296,14 @@
bool trace_compiler: false,
bool verbose_vm: false,
bool pause_on_unhandled_exceptions: false,
- bool testeeControlsServer: false}) {
+ bool testeeControlsServer: false,
+ bool useAuthToken: false}) {
var process = new _ServiceTesteeLauncher();
process.launch(pause_on_start, pause_on_exit,
pause_on_unhandled_exceptions,
trace_service, trace_compiler,
- testeeControlsServer).then((Uri serverAddress) async {
+ testeeControlsServer,
+ useAuthToken).then((Uri serverAddress) async {
if (mainArgs.contains("--gdb")) {
var pid = process.process.pid;
var wait = new Duration(seconds: 10);
@@ -348,7 +368,8 @@
bool trace_compiler: false,
bool verbose_vm: false,
bool pause_on_unhandled_exceptions: false,
- bool testeeControlsServer: false}) async {
+ bool testeeControlsServer: false,
+ bool useAuthToken: false}) async {
assert(!pause_on_start || testeeBefore == null);
if (_isTestee()) {
new _ServiceTesteeRunner().run(testeeBefore: testeeBefore,
@@ -365,7 +386,8 @@
trace_compiler: trace_compiler,
verbose_vm: verbose_vm,
pause_on_unhandled_exceptions: pause_on_unhandled_exceptions,
- testeeControlsServer: testeeControlsServer);
+ testeeControlsServer: testeeControlsServer,
+ useAuthToken: useAuthToken);
}
}
diff --git a/runtime/vm/cpu_arm.cc b/runtime/vm/cpu_arm.cc
index be88185..a0e31a9 100644
--- a/runtime/vm/cpu_arm.cc
+++ b/runtime/vm/cpu_arm.cc
@@ -199,17 +199,20 @@
// - Qualcomm Krait CPUs (QCT APQ8064) in Nexus 4 and 7 incorrectly report
// that they lack integer division.
// - Marvell Armada 370/XP incorrectly reports that it has integer division.
+ // - The Pixel lacks integer division even though ARMv8 requires it in A32.
bool is_krait = CpuInfo::FieldContains(kCpuInfoHardware, "QCT APQ8064");
bool is_armada_370xp =
CpuInfo::FieldContains(kCpuInfoHardware, "Marvell Armada 370/XP");
+ bool is_pixel =
+ CpuInfo::FieldContains(kCpuInfoHardware, "MSM8996pro");
if (is_krait) {
integer_division_supported_ = FLAG_use_integer_division;
- } else if (!is_armada_370xp) {
+ } else if (is_armada_370xp || is_pixel) {
+ integer_division_supported_ = false;
+ } else {
integer_division_supported_ =
(CpuInfo::FieldContains(kCpuInfoFeatures, "idiva") || is_arm64) &&
FLAG_use_integer_division;
- } else {
- integer_division_supported_ = false;
}
neon_supported_ =
(CpuInfo::FieldContains(kCpuInfoFeatures, "neon") || is_arm64) &&
diff --git a/runtime/vm/dart_api_impl.cc b/runtime/vm/dart_api_impl.cc
index 343f597..e1c2aca 100644
--- a/runtime/vm/dart_api_impl.cc
+++ b/runtime/vm/dart_api_impl.cc
@@ -5718,6 +5718,42 @@
}
+DART_EXPORT Dart_Handle Dart_GetImportsOfScheme(Dart_Handle scheme) {
+ DARTSCOPE(Thread::Current());
+ Isolate* I = T->isolate();
+ const String& scheme_vm = Api::UnwrapStringHandle(Z, scheme);
+ if (scheme_vm.IsNull()) {
+ RETURN_TYPE_ERROR(Z, scheme, String);
+ }
+
+ const GrowableObjectArray& libraries =
+ GrowableObjectArray::Handle(Z, I->object_store()->libraries());
+ const GrowableObjectArray& result =
+ GrowableObjectArray::Handle(Z, GrowableObjectArray::New());
+ Library& importer = Library::Handle(Z);
+ Array& imports = Array::Handle(Z);
+ Namespace& ns = Namespace::Handle(Z);
+ Library& importee = Library::Handle(Z);
+ String& importee_uri = String::Handle(Z);
+ for (intptr_t i = 0; i < libraries.Length(); i++) {
+ importer ^= libraries.At(i);
+ imports = importer.imports();
+ for (intptr_t j = 0; j < imports.Length(); j++) {
+ ns ^= imports.At(j);
+ if (ns.IsNull()) continue;
+ importee = ns.library();
+ importee_uri = importee.url();
+ if (importee_uri.StartsWith(scheme_vm)) {
+ result.Add(importer);
+ result.Add(importee);
+ }
+ }
+ }
+
+ return Api::NewHandle(T, Array::MakeArray(result));
+}
+
+
DART_EXPORT Dart_Handle Dart_LoadSource(Dart_Handle library,
Dart_Handle url,
Dart_Handle resolved_url,
diff --git a/runtime/vm/kernel_to_il.cc b/runtime/vm/kernel_to_il.cc
index 38900f1..02f5437 100644
--- a/runtime/vm/kernel_to_il.cc
+++ b/runtime/vm/kernel_to_il.cc
@@ -30,6 +30,33 @@
#define I Isolate::Current()
+static void DiscoverEnclosingElements(Zone* zone,
+ const Function& function,
+ Function* outermost_function,
+ TreeNode** outermost_node,
+ Class** klass) {
+ // Find out if there is an enclosing kernel class (which will be used to
+ // resolve type parameters).
+ *outermost_function = function.raw();
+ while (outermost_function->parent_function() != Object::null()) {
+ *outermost_function = outermost_function->parent_function();
+ }
+ *outermost_node =
+ static_cast<TreeNode*>(outermost_function->kernel_function());
+ if (*outermost_node != NULL) {
+ TreeNode* parent = NULL;
+ if ((*outermost_node)->IsProcedure()) {
+ parent = Procedure::Cast(*outermost_node)->parent();
+ } else if ((*outermost_node)->IsConstructor()) {
+ parent = Constructor::Cast(*outermost_node)->parent();
+ } else if ((*outermost_node)->IsField()) {
+ parent = Field::Cast(*outermost_node)->parent();
+ }
+ if (parent != NULL && parent->IsClass()) *klass = Class::Cast(parent);
+ }
+}
+
+
void ScopeBuilder::EnterScope(TreeNode* node) {
scope_ = new (Z) LocalScope(scope_, depth_.function_, depth_.loop_);
result_->scopes.Insert(node, scope_);
@@ -39,17 +66,8 @@
void ScopeBuilder::ExitScope() { scope_ = scope_->parent(); }
-LocalVariable* ScopeBuilder::MakeVariable(const dart::String& name) {
- return new (Z)
- LocalVariable(TokenPosition::kNoSource,
- TokenPosition::kNoSource,
- name,
- Object::dynamic_type());
-}
-
-
LocalVariable* ScopeBuilder::MakeVariable(const dart::String& name,
- const Type& type) {
+ const AbstractType& type) {
return new (Z) LocalVariable(TokenPosition::kNoSource,
TokenPosition::kNoSource,
name,
@@ -71,7 +89,9 @@
void ScopeBuilder::AddParameter(VariableDeclaration* declaration,
intptr_t pos) {
- LocalVariable* variable = MakeVariable(H.DartSymbol(declaration->name()));
+ LocalVariable* variable =
+ MakeVariable(H.DartSymbol(declaration->name()),
+ T.TranslateVariableType(declaration));
if (declaration->IsFinal()) {
variable->set_is_final();
}
@@ -117,7 +137,8 @@
// If variable was not lifted by the transformer introduce a new
// one into the current function scope.
if (v == NULL) {
- v = MakeVariable(GenerateName(prefix, nesting_depth - 1));
+ v = MakeVariable(GenerateName(prefix, nesting_depth - 1),
+ AbstractType::dynamic_type());
// If transformer did not lift the variable then there is no need
// to lift it into the context when we encouter a YieldStatement.
@@ -149,7 +170,8 @@
ASSERT(result_->iterator_variables.length() == depth_.for_in_ - 1);
LocalVariable* iterator =
- MakeVariable(GenerateName(":iterator", depth_.for_in_ - 1));
+ MakeVariable(GenerateName(":iterator", depth_.for_in_ - 1),
+ AbstractType::dynamic_type());
current_function_scope_->AddVariable(iterator);
result_->iterator_variables.Add(iterator);
}
@@ -213,7 +235,8 @@
const dart::String& name = declaration->name()->is_empty()
? GenerateName(":var", name_index_++)
: H.DartSymbol(declaration->name());
- LocalVariable* variable = MakeVariable(name);
+ LocalVariable* variable =
+ MakeVariable(name, T.TranslateVariableType(declaration));
if (declaration->IsFinal()) {
variable->set_is_final();
}
@@ -238,6 +261,25 @@
ParsedFunction* parsed_function = parsed_function_;
const dart::Function& function = parsed_function->function();
+ // Setup a [ActiveClassScope] and a [ActiveMemberScope] which will be used
+ // e.g. for type translation.
+ const dart::Class& klass =
+ dart::Class::Handle(zone_, parsed_function_->function().Owner());
+ Function& outermost_function = Function::Handle(Z);
+ TreeNode* outermost_node = NULL;
+ Class* kernel_klass = NULL;
+ DiscoverEnclosingElements(
+ Z, function, &outermost_function, &outermost_node, &kernel_klass);
+ // Use [klass]/[kernel_klass] as active class. Type parameters will get
+ // resolved via [kernel_klass] unless we are nested inside a static factory
+ // in which case we will use [member].
+ ActiveClassScope active_class_scope(&active_class_, kernel_klass, &klass);
+ Member* member = ((outermost_node != NULL) && outermost_node->IsMember())
+ ? Member::Cast(outermost_node)
+ : NULL;
+ ActiveMemberScope active_member(&active_class_, member);
+
+
LocalScope* enclosing_scope = NULL;
if (function.IsLocalFunction()) {
enclosing_scope = LocalScope::RestoreOuterScope(
@@ -271,7 +313,9 @@
intptr_t pos = 0;
if (function.IsClosureFunction()) {
- LocalVariable* variable = MakeVariable(Symbols::ClosureParameter());
+ LocalVariable* variable =
+ MakeVariable(Symbols::ClosureParameter(),
+ AbstractType::dynamic_type());
variable->set_is_forced_stack();
scope_->InsertParameterAt(pos++, variable);
} else if (!function.is_static()) {
@@ -299,7 +343,8 @@
}
} else if (function.IsFactory()) {
LocalVariable* variable = MakeVariable(
- Symbols::TypeArgumentsParameter(), AbstractType::dynamic_type());
+ Symbols::TypeArgumentsParameter(),
+ AbstractType::dynamic_type());
scope_->InsertParameterAt(pos++, variable);
result_->type_arguments_variable = variable;
}
@@ -332,7 +377,8 @@
result_->this_variable = variable;
}
if (is_setter) {
- result_->setter_value = MakeVariable(Symbols::Value());
+ result_->setter_value = MakeVariable(
+ Symbols::Value(), AbstractType::dynamic_type());
scope_->InsertParameterAt(pos++, result_->setter_value);
}
break;
@@ -353,7 +399,8 @@
case RawFunction::kInvokeFieldDispatcher:
for (intptr_t i = 0; i < function.NumParameters(); ++i) {
LocalVariable* variable = MakeVariable(
- dart::String::ZoneHandle(Z, function.ParameterNameAt(i)));
+ dart::String::ZoneHandle(Z, function.ParameterNameAt(i)),
+ AbstractType::dynamic_type());
scope_->InsertParameterAt(i, variable);
}
break;
@@ -528,7 +575,9 @@
void ScopeBuilder::AddSwitchVariable() {
if ((depth_.function_ == 0) && (result_->switch_variable == NULL)) {
- LocalVariable* variable = MakeVariable(Symbols::SwitchExpr());
+ LocalVariable* variable = MakeVariable(
+ Symbols::SwitchExpr(),
+ AbstractType::dynamic_type());
variable->set_is_forced_stack();
current_function_scope_->AddVariable(variable);
result_->switch_variable = variable;
@@ -546,7 +595,9 @@
if ((depth_.function_ == 0) && (depth_.finally_ > 0) &&
(result_->finally_return_variable == NULL)) {
const dart::String& name = H.DartSymbol(":try_finally_return_value");
- LocalVariable* variable = MakeVariable(name);
+ LocalVariable* variable = MakeVariable(
+ name,
+ AbstractType::dynamic_type());
current_function_scope_->AddVariable(variable);
result_->finally_return_variable = variable;
}
@@ -2731,34 +2782,18 @@
dart::Class& klass =
dart::Class::Handle(zone_, parsed_function_->function().Owner());
- // Find out if there is an enclosing kernel class (which will be used to
- // resolve type parameters).
+ Function& outermost_function = Function::Handle(Z);
+ TreeNode* outermost_node = NULL;
Class* kernel_klass = NULL;
- dart::Function& topmost = dart::Function::Handle(Z, function.raw());
- while (topmost.parent_function() != Object::null()) {
- topmost = topmost.parent_function();
- }
- TreeNode* topmost_node = static_cast<TreeNode*>(topmost.kernel_function());
- if (topmost_node != NULL) {
- // Going up the closure->parent chain needs to result in a Procedure or
- // Constructor.
- TreeNode* parent = NULL;
- if (topmost_node->IsProcedure()) {
- parent = Procedure::Cast(topmost_node)->parent();
- } else if (topmost_node->IsConstructor()) {
- parent = Constructor::Cast(topmost_node)->parent();
- } else if (topmost_node->IsField()) {
- parent = Field::Cast(topmost_node)->parent();
- }
- if (parent != NULL && parent->IsClass()) kernel_klass = Class::Cast(parent);
- }
+ DiscoverEnclosingElements(
+ Z, function, &outermost_function, &outermost_node, &kernel_klass);
// Mark that we are using [klass]/[kernell_klass] as active class. Resolving
// of type parameters will get resolved via [kernell_klass] unless we are
// nested inside a static factory in which case we will use [member].
ActiveClassScope active_class_scope(&active_class_, kernel_klass, &klass);
- Member* member = topmost_node != NULL && topmost_node->IsMember()
- ? Member::Cast(topmost_node)
+ Member* member = ((outermost_node != NULL) && outermost_node->IsMember())
+ ? Member::Cast(outermost_node)
: NULL;
ActiveMemberScope active_member(&active_class_, member);
@@ -2846,12 +2881,12 @@
LocalVariable* variable = scope->VariableAt(i);
if (variable->is_captured()) {
// There is no LocalVariable describing the on-stack parameter so
- // create one directly.
+ // create one directly and use the same type.
LocalVariable* parameter =
new (Z) LocalVariable(TokenPosition::kNoSource,
TokenPosition::kNoSource,
Symbols::TempParam(),
- Object::dynamic_type());
+ variable->type());
parameter->set_index(parameter_index);
// Mark the stack variable so it will be ignored by the code for
// try/catch.
@@ -3804,6 +3839,24 @@
}
+const AbstractType& DartTypeTranslator::TranslateVariableType(
+ VariableDeclaration* variable) {
+ AbstractType& abstract_type = TranslateType(variable->type());
+
+ // We return a new `ZoneHandle` here on purpose: The intermediate language
+ // instructions do not make a copy of the handle, so we do it.
+ AbstractType& type = Type::ZoneHandle(Z);
+
+ if (abstract_type.IsMalformed()) {
+ type = AbstractType::dynamic_type().raw();
+ } else {
+ type = result_.raw();
+ }
+
+ return type;
+}
+
+
void DartTypeTranslator::VisitInvalidType(InvalidType* node) {
result_ = ClassFinalizer::NewFinalizedMalformedType(
Error::Handle(Z), // No previous error.
diff --git a/runtime/vm/kernel_to_il.h b/runtime/vm/kernel_to_il.h
index eb3beca..6a62834 100644
--- a/runtime/vm/kernel_to_il.h
+++ b/runtime/vm/kernel_to_il.h
@@ -296,6 +296,9 @@
// Can return a malformed type.
AbstractType& TranslateTypeWithoutFinalization(DartType* node);
+ // Is guaranteed to be not malformed.
+ const AbstractType& TranslateVariableType(VariableDeclaration* variable);
+
virtual void VisitDefaultDartType(DartType* node) { UNREACHABLE(); }
@@ -494,6 +497,7 @@
node_(node),
zone_(Thread::Current()->zone()),
translation_helper_(Thread::Current(), zone_, Isolate::Current()),
+ type_translator_(&translation_helper_, &active_class_),
current_function_scope_(NULL),
scope_(NULL),
depth_(0),
@@ -534,8 +538,9 @@
void EnterScope(TreeNode* node);
void ExitScope();
- LocalVariable* MakeVariable(const dart::String& name);
- LocalVariable* MakeVariable(const dart::String& name, const Type& type);
+ const Type& TranslateVariableType(VariableDeclaration* variable);
+ LocalVariable* MakeVariable(const dart::String& name,
+ const AbstractType& type);
void AddParameters(FunctionNode* function, intptr_t pos = 0);
void AddParameter(VariableDeclaration* declaration, intptr_t pos);
@@ -581,9 +586,11 @@
ParsedFunction* parsed_function_;
TreeNode* node_;
+ ActiveClass active_class_;
+
Zone* zone_;
TranslationHelper translation_helper_;
-
+ DartTypeTranslator type_translator_;
FunctionNode* current_function_node_;
LocalScope* current_function_scope_;
diff --git a/runtime/vm/simulator_dbc.cc b/runtime/vm/simulator_dbc.cc
index c02e1bf..a34d93b 100644
--- a/runtime/vm/simulator_dbc.cc
+++ b/runtime/vm/simulator_dbc.cc
@@ -38,6 +38,7 @@
"Instruction address or instruction count to stop simulator at.");
#define LIKELY(cond) __builtin_expect((cond), 1)
+#define UNLIKELY(cond) __builtin_expect((cond), 0)
// SimulatorSetjmpBuffer are linked together, and the last created one
// is referenced by the Simulator. When an exception is thrown, the exception
@@ -1435,9 +1436,17 @@
counter += increment;
f->ptr()->usage_counter_ = counter;
}
- if (counter >= threshold) {
+ if (UNLIKELY(counter >= threshold)) {
FP[0] = f;
FP[1] = 0;
+
+ // Make the DRT_OptimizeInvokedFunction see a stub as its caller for
+ // consistency with the other architectures, and to avoid needing to
+ // generate a stackmap for the HotCheck pc.
+ const StubEntry* stub = StubCode::OptimizeFunction_entry();
+ FP[kPcMarkerSlotFromFp] = stub->code();
+ pc = reinterpret_cast<uint32_t*>(stub->EntryPoint());
+
Exit(thread, FP, FP + 2, pc);
NativeArguments args(thread, 1, FP, FP + 1);
INVOKE_RUNTIME(DRT_OptimizeInvokedFunction, args);
@@ -1983,7 +1992,7 @@
{
BYTECODE(Shl, A_B_C);
const intptr_t rhs = reinterpret_cast<intptr_t>(FP[rC]) >> kSmiTagSize;
- if (rhs >= 0) {
+ if (static_cast<uintptr_t>(rhs) < kBitsPerWord) {
const intptr_t lhs = reinterpret_cast<intptr_t>(FP[rB]);
const intptr_t res = lhs << rhs;
if (lhs == (res >> rhs)) {
diff --git a/runtime/vm/stub_code.h b/runtime/vm/stub_code.h
index 7b51f9f..d183296 100644
--- a/runtime/vm/stub_code.h
+++ b/runtime/vm/stub_code.h
@@ -72,6 +72,7 @@
#else
#define VM_STUB_CODE_LIST(V) \
V(LazyCompile) \
+ V(OptimizeFunction) \
V(FixCallersTarget) \
V(Deoptimize) \
V(DeoptimizeLazyFromReturn) \
diff --git a/runtime/vm/stub_code_dbc.cc b/runtime/vm/stub_code_dbc.cc
index 1f2d23e..81a83d6 100644
--- a/runtime/vm/stub_code_dbc.cc
+++ b/runtime/vm/stub_code_dbc.cc
@@ -32,6 +32,13 @@
}
+// Not executed, but used as a stack marker when calling
+// DRT_OptimizeInvokedFunction.
+void StubCode::GenerateOptimizeFunctionStub(Assembler* assembler) {
+ __ Trap();
+}
+
+
// TODO(vegorov) Don't generate this stub.
void StubCode::GenerateFixCallersTargetStub(Assembler* assembler) {
__ Trap();
diff --git a/runtime/vm/thread_pool_test.cc b/runtime/vm/thread_pool_test.cc
index 48d2125..a555503 100644
--- a/runtime/vm/thread_pool_test.cc
+++ b/runtime/vm/thread_pool_test.cc
@@ -23,7 +23,17 @@
: sync_(sync), done_(done) {
}
+ // Before running the task, *done_ should be true. This lets the caller
+ // ASSERT things knowing that the thread is still around. To unblock the
+ // thread, the caller should take the lock, set *done_ to false, and Notify()
+ // the monitor.
virtual void Run() {
+ {
+ MonitorLocker ml(sync_);
+ while (*done_) {
+ ml.Wait();
+ }
+ }
MonitorLocker ml(sync_);
*done_ = true;
ml.Notify();
@@ -38,10 +48,12 @@
UNIT_TEST_CASE(ThreadPool_RunOne) {
ThreadPool thread_pool;
Monitor sync;
- bool done = false;
+ bool done = true;
thread_pool.Run(new TestTask(&sync, &done));
{
MonitorLocker ml(&sync);
+ done = false;
+ ml.Notify();
while (!done) {
ml.Wait();
}
@@ -61,11 +73,13 @@
bool done[kTaskCount];
for (int i = 0; i < kTaskCount; i++) {
- done[i] = false;
+ done[i] = true;
thread_pool.Run(new TestTask(&sync[i], &done[i]));
}
for (int i = 0; i < kTaskCount; i++) {
MonitorLocker ml(&sync[i]);
+ done[i] = false;
+ ml.Notify();
while (!done[i]) {
ml.Wait();
}
@@ -157,12 +171,14 @@
// Run a worker.
Monitor sync;
- bool done = false;
+ bool done = true;
thread_pool.Run(new TestTask(&sync, &done));
EXPECT_EQ(1U, thread_pool.workers_started());
EXPECT_EQ(0U, thread_pool.workers_stopped());
{
MonitorLocker ml(&sync);
+ done = false;
+ ml.Notify();
while (!done) {
ml.Wait();
}
diff --git a/samples/sample_extension/test/sample_extension_app_snapshot_test.dart b/samples/sample_extension/test/sample_extension_app_snapshot_test.dart
new file mode 100644
index 0000000..04193c9
--- /dev/null
+++ b/samples/sample_extension/test/sample_extension_app_snapshot_test.dart
@@ -0,0 +1,11 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+//
+// Dart test program for testing native extensions.
+
+import 'sample_extension_test_helper.dart';
+
+void main() {
+ testNativeExtensions("app-jit");
+}
diff --git a/samples/sample_extension/test/sample_extension_script_snapshot_test.dart b/samples/sample_extension/test/sample_extension_script_snapshot_test.dart
new file mode 100644
index 0000000..31b9e03
--- /dev/null
+++ b/samples/sample_extension/test/sample_extension_script_snapshot_test.dart
@@ -0,0 +1,11 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+//
+// Dart test program for testing native extensions.
+
+import 'sample_extension_test_helper.dart';
+
+void main() {
+ testNativeExtensions("script");
+}
diff --git a/samples/sample_extension/test/sample_extension_test.dart b/samples/sample_extension/test/sample_extension_test.dart
index 9c0a42d..4311ff5 100644
--- a/samples/sample_extension/test/sample_extension_test.dart
+++ b/samples/sample_extension/test/sample_extension_test.dart
@@ -1,72 +1,11 @@
-// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Dart test program for testing native extensions.
-import 'dart:async';
-import 'dart:io';
-import 'dart:isolate';
-
-import "package:expect/expect.dart";
-import "package:path/path.dart";
-
-Future copyFileToDirectory(String file, String directory) {
- String src = file;
- String dst = directory;
- switch (Platform.operatingSystem) {
- case 'linux':
- case 'macos':
- return Process.run('cp', [src, dst]);
- case 'windows':
- return Process.run('cmd.exe', ['/C', 'copy $src $dst']);
- default:
- Expect.fail('Unknown operating system ${Platform.operatingSystem}');
- }
-}
-
-String getNativeLibraryPath(String buildDirectory) {
- switch (Platform.operatingSystem) {
- case 'linux':
- return join(buildDirectory, 'lib.target', 'libsample_extension.so');
- case 'macos':
- return join(buildDirectory, 'libsample_extension.dylib');
- case 'windows':
- return join(buildDirectory, 'sample_extension.dll');
- default:
- Expect.fail('Unknown operating system ${Platform.operatingSystem}');
- }
-}
+import 'sample_extension_test_helper.dart';
void main() {
- String buildDirectory = dirname(Platform.executable);
- Directory tempDirectory =
- Directory.systemTemp.createTempSync('sample_extension_');
- String testDirectory = tempDirectory.path;
- String sourceDirectory = Platform.script.resolve('..').toFilePath();
-
- // Copy sample_extension shared library, sample_extension dart files and
- // sample_extension tests to the temporary test directory.
- copyFileToDirectory(getNativeLibraryPath(buildDirectory), testDirectory)
- .then((_) => Future.forEach(['sample_synchronous_extension.dart',
- 'sample_asynchronous_extension.dart',
- 'test_sample_synchronous_extension.dart',
- 'test_sample_asynchronous_extension.dart'],
- (file) => copyFileToDirectory(join(sourceDirectory, file), testDirectory)
- ))
-
- .then((_) => Future.forEach(['test_sample_synchronous_extension.dart',
- 'test_sample_asynchronous_extension.dart'],
- (test) => Process.run(Platform.executable, [join(testDirectory, test)])
- .then((ProcessResult result) {
- if (result.exitCode != 0) {
- print('Failing test: ${join(sourceDirectory, test)}');
- print('Failing process stdout: ${result.stdout}');
- print('Failing process stderr: ${result.stderr}');
- print('End failing process stderr');
- Expect.fail('Test failed with exit code ${result.exitCode}');
- }
- })
- ))
- .whenComplete(() => tempDirectory.deleteSync(recursive: true));
+ testNativeExtensions(null /* no snapshot */);
}
diff --git a/samples/sample_extension/test/sample_extension_test_helper.dart b/samples/sample_extension/test/sample_extension_test_helper.dart
new file mode 100644
index 0000000..e1c1faa
--- /dev/null
+++ b/samples/sample_extension/test/sample_extension_test_helper.dart
@@ -0,0 +1,90 @@
+// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+//
+// Dart test program for testing native extensions.
+
+import 'dart:async';
+import 'dart:io';
+import 'dart:isolate';
+
+import "package:expect/expect.dart";
+import "package:path/path.dart";
+
+Future copyFileToDirectory(String file, String directory) {
+ String src = file;
+ String dst = directory;
+ switch (Platform.operatingSystem) {
+ case 'linux':
+ case 'macos':
+ return Process.run('cp', [src, dst]);
+ case 'windows':
+ return Process.run('cmd.exe', ['/C', 'copy $src $dst']);
+ default:
+ Expect.fail('Unknown operating system ${Platform.operatingSystem}');
+ }
+}
+
+String getNativeLibraryPath(String buildDirectory) {
+ switch (Platform.operatingSystem) {
+ case 'linux':
+ return join(buildDirectory, 'lib.target', 'libsample_extension.so');
+ case 'macos':
+ return join(buildDirectory, 'libsample_extension.dylib');
+ case 'windows':
+ return join(buildDirectory, 'sample_extension.dll');
+ default:
+ Expect.fail('Unknown operating system ${Platform.operatingSystem}');
+ }
+}
+
+Future run(String program, List arguments) async {
+ print("+ $program ${arguments.join(' ')}");
+ ProcessResult result = await Process.run(program, arguments);
+ if (result.exitCode != 0) {
+ print('Failing process stdout: ${result.stdout}');
+ print('Failing process stderr: ${result.stderr}');
+ print('End failing process stderr');
+ Expect.fail('Test failed with exit code ${result.exitCode}');
+ }
+}
+
+Future testNativeExtensions(String snapshotKind) async {
+ String buildDirectory = dirname(Platform.executable);
+ Directory tempDirectory =
+ Directory.systemTemp.createTempSync('sample_extension_');
+ try {
+ String testDirectory = tempDirectory.path;
+ String sourceDirectory = Platform.script.resolve('..').toFilePath();
+
+ // Copy sample_extension shared library, sample_extension dart files and
+ // sample_extension tests to the temporary test directory.
+ await copyFileToDirectory(getNativeLibraryPath(buildDirectory),
+ testDirectory);
+ for (var file in ['sample_synchronous_extension.dart',
+ 'sample_asynchronous_extension.dart',
+ 'test_sample_synchronous_extension.dart',
+ 'test_sample_asynchronous_extension.dart']) {
+ await copyFileToDirectory(join(sourceDirectory, file), testDirectory);
+ }
+
+ for (var test in ['test_sample_synchronous_extension.dart',
+ 'test_sample_asynchronous_extension.dart']) {
+ String script = join(testDirectory, test);
+ String snapshot;
+ if (snapshotKind == null) {
+ snapshot = script;
+ } else {
+ snapshot = join(testDirectory, "$test.snapshot");
+ await run(Platform.executable,
+ ['--snapshot=$snapshot',
+ '--snapshot-kind=$snapshotKind',
+ script]);
+ }
+
+ await run(Platform.executable, [snapshot]);
+ }
+ } finally {
+ await tempDirectory.deleteSync(recursive: true);
+ }
+}
diff --git a/samples/samples.status b/samples/samples.status
index c01c0d9..02b193f 100644
--- a/samples/samples.status
+++ b/samples/samples.status
@@ -19,10 +19,7 @@
build_dart: Skip
[ $arch == arm ]
-sample_extension/test/sample_extension_test: Skip # Issue 14705
-
-[ $arch == simarm64 ]
-*: Skip
+sample_extension/test/*: Skip # Issue 14705
[ $noopt || $runtime == dart_precompiled || $runtime == dart_app ]
sample_extension: Skip # Platform.executable
diff --git a/sdk/lib/async/stream.dart b/sdk/lib/async/stream.dart
index 4f0d9f0..f114f8d 100644
--- a/sdk/lib/async/stream.dart
+++ b/sdk/lib/async/stream.dart
@@ -903,23 +903,23 @@
=> listen(null, cancelOnError: true).asFuture/*<E>*/(futureValue);
/**
- * Provides at most the first [n] values of this stream.
+ * Provides at most the first [count] data events of this stream.
*
- * Forwards the first [n] data events of this stream, and all error
- * events, to the returned stream, and ends with a done event.
+ * Forwards all events of this stream to the returned stream
+ * until [count] data events have been forwarded or this stream ends,
+ * then ends the returned stream with a done event.
*
- * If this stream produces fewer than [count] values before it's done,
+ * If this stream produces fewer than [count] data events before it's done,
* so will the returned stream.
*
- * Stops listening to the stream after the first [n] elements have been
- * received.
+ * Starts listening to this stream when the returned stream is listened to
+ * and stops listening when the first [count] data events have been received.
*
- * Internally the method cancels its subscription after these elements. This
- * means that single-subscription (non-broadcast) streams are closed and
- * cannot be reused after a call to this method.
+ * This means that if this is a single-subscription (non-broadcast) streams
+ * it cannot be reused after the returned stream has been listened to.
*
- * The returned stream is a broadcast stream if this stream is.
- * For a broadcast stream, the events are only counted from the time
+ * If this is a broadcast stream, the returned stream is a broadcast stream.
+ * In that case, the events are only counted from the time
* the returned stream is listened to.
*/
Stream<T> take(int count) {
@@ -930,7 +930,7 @@
* Forwards data events while [test] is successful.
*
* The returned stream provides the same events as this stream as long
- * as [test] returns [:true:] for the event data. The stream is done
+ * as [test] returns `true` for the event data. The stream is done
* when either this stream is done, or when this stream first provides
* a value that [test] doesn't accept.
*
diff --git a/sdk/lib/async/stream_pipe.dart b/sdk/lib/async/stream_pipe.dart
index d26b0c5..643d142 100644
--- a/sdk/lib/async/stream_pipe.dart
+++ b/sdk/lib/async/stream_pipe.dart
@@ -326,6 +326,10 @@
Function onError,
void onDone(),
bool cancelOnError) {
+ if (_count == 0) {
+ _source.listen(null).cancel();
+ return new _DoneStreamSubscription<T>(onDone);
+ }
return new _StateStreamSubscription<T>(
this, onData, onError, onDone, cancelOnError, _count);
}
diff --git a/sdk/lib/convert/codec.dart b/sdk/lib/convert/codec.dart
index 3fc2d31..7f42c86 100644
--- a/sdk/lib/convert/codec.dart
+++ b/sdk/lib/convert/codec.dart
@@ -62,8 +62,8 @@
*/
// TODO(floitsch): use better example with line-splitter once that one is
// in this library.
- Codec<S, dynamic> fuse(Codec<T, dynamic> other) {
- return new _FusedCodec<S, T, dynamic>(this, other);
+ Codec<S, dynamic/*=R*/> fuse/*<R>*/(Codec<T, dynamic/*=R*/> other) {
+ return new _FusedCodec<S, T, dynamic/*=R*/>(this, other);
}
/**
diff --git a/sdk/lib/vmservice/vmservice.dart b/sdk/lib/vmservice/vmservice.dart
index 41e8017..0330233 100644
--- a/sdk/lib/vmservice/vmservice.dart
+++ b/sdk/lib/vmservice/vmservice.dart
@@ -42,7 +42,7 @@
final String serviceAuthToken = _makeAuthToken();
// TODO(johnmccutchan): Enable the auth token and drop the origin check.
-final bool useAuthToken = false;
+final bool useAuthToken = const bool.fromEnvironment('DART_SERVICE_USE_AUTH');
// This is for use by the embedder. It is a map from the isolateId to
// anything implementing IsolateEmbedderData. When an isolate goes away,
diff --git a/tests/co19/co19-co19.status b/tests/co19/co19-co19.status
index f1ccde4..1b57b2e 100644
--- a/tests/co19/co19-co19.status
+++ b/tests/co19/co19-co19.status
@@ -29,6 +29,8 @@
LibTest/collection/MapMixin/MapMixin_class_A01_t01: Fail # co19 issue 72
[ $compiler != dart2analyzer ]
+LibTest/isolate/ReceivePort/take_A01_t02: Fail # co19 issue 81
+LibTest/async/Stream/take_A01_t02: Fail # co19 issue 81
# Tests that fail on every runtime, but not on the analyzer.
Language/Classes/same_name_type_variable_t04: Pass, MissingCompileTimeError, Fail # Issue 14513,25525
Language/Classes/same_name_type_variable_t07: Pass, MissingCompileTimeError, Fail # Issue 14513,25525
diff --git a/tests/co19/co19-runtime.status b/tests/co19/co19-runtime.status
index d4ee097..24d95eb 100644
--- a/tests/co19/co19-runtime.status
+++ b/tests/co19/co19-runtime.status
@@ -50,7 +50,7 @@
LibTest/core/List/List_class_A01_t02: Pass, Slow
Language/Libraries_and_Scripts/Imports/deferred_import_t02: Crash # Issue 27201
-[ ($runtime == vm || $runtime == dart_precompiled || $runtime == dart_app) && ($arch != x64 && $arch != simarm64 && $arch != arm64 && $arch != simdbc64) ]
+[ ($runtime == vm || $runtime == dart_precompiled || $runtime == dart_app) && ($arch != x64 && $arch != simarm64 && $arch != arm64 && $arch != simdbc64 && $arch != simdbc) ]
LibTest/core/int/operator_left_shift_A01_t02: Fail # co19 issue 129
[ ($compiler == none || $compiler == precompiler) && ($runtime == vm || $runtime == dart_precompiled) && ($arch == mips || $arch == arm64) ]
@@ -225,4 +225,4 @@
LibTest/core/Uri/Uri_A06_t03: Pass, Timeout
LibTest/core/Uri/encodeQueryComponent_A01_t02: Pass, Timeout
LibTest/isolate/Isolate/spawn_A01_t04: Pass, Timeout
-
+LibTest/isolate/ReceivePort/take_A01_t02: Crash, Fail # Issue 27773
diff --git a/tests/compiler/dart2js/dart2js.status b/tests/compiler/dart2js/dart2js.status
index 7900590..9b3a477 100644
--- a/tests/compiler/dart2js/dart2js.status
+++ b/tests/compiler/dart2js/dart2js.status
@@ -8,8 +8,6 @@
kernel/*: Slow, Pass
-kernel/visitor_test: Fail # Issue 27684
-
boolified_operator_test: Fail # Issue 8001
# Don't mark these tests as failing. Instead, fix the errors/warnings that they
diff --git a/tests/compiler/dart2js/kernel/class_hierarchy_test.dart b/tests/compiler/dart2js/kernel/class_hierarchy_test.dart
new file mode 100644
index 0000000..9b6aa08
--- /dev/null
+++ b/tests/compiler/dart2js/kernel/class_hierarchy_test.dart
@@ -0,0 +1,76 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+/// Test that the dart2js copy of [KernelVisitor] generates the expected class
+/// hierarchy.
+
+import 'package:compiler/src/compiler.dart' show Compiler;
+import 'package:compiler/src/elements/elements.dart';
+import 'package:compiler/src/js_backend/backend.dart' show JavaScriptBackend;
+import 'package:compiler/src/commandline_options.dart' show Flags;
+import 'package:kernel/ast.dart' as ir;
+import 'package:kernel/class_hierarchy.dart';
+import 'package:test/test.dart';
+
+import '../memory_compiler.dart';
+
+main(List<String> arguments) {
+ Compiler compiler = compilerFor(memorySourceFiles: {
+ 'main.dart': '''
+ class S {
+ sMethod() {}
+ }
+ class M {
+ mMethod() {}
+ }
+ class C extends S with M {
+ cMethod() {}
+ }
+ main() {}
+ '''
+ }, options: [
+ Flags.analyzeOnly,
+ Flags.analyzeMain,
+ Flags.useKernel
+ ]);
+ test('mixin', () async {
+ Uri mainUri = Uri.parse('memory:main.dart');
+ LibraryElement library = await compiler.analyzeUri(mainUri);
+ JavaScriptBackend backend = compiler.backend;
+ ir.Program program = backend.kernelTask.buildProgram(library);
+ ClassHierarchy hierarchy = new ClassHierarchy(program);
+
+ ir.Class getClass(String name) {
+ for (ir.Class cls in hierarchy.classes) {
+ if (cls.enclosingLibrary.importUri == mainUri && cls.name == name) {
+ if (arguments.contains('-v')) {
+ print('$cls');
+ print(' dispatch targets:');
+ hierarchy
+ .getDispatchTargets(cls)
+ .forEach((member) => print(' $member'));
+ }
+ return cls;
+ }
+ }
+ fail('Class $name not found.');
+ }
+
+ ir.Class classS = getClass('S');
+ ir.Class classM = getClass('M');
+ ir.Class classC = getClass('C');
+
+ void checkInheritance(ir.Class superClass, ir.Class subClass) {
+ for (ir.Member member in hierarchy.getDispatchTargets(superClass)) {
+ expect(
+ hierarchy.getDispatchTarget(subClass, member.name), equals(member),
+ reason: 'Unexpected dispatch target for ${member.name} '
+ 'in $subClass');
+ }
+ }
+
+ checkInheritance(classS, classC);
+ checkInheritance(classM, classC);
+ });
+}
diff --git a/tests/compiler/dart2js/kernel/impact_test.dart b/tests/compiler/dart2js/kernel/impact_test.dart
index 60a95b9..363f44d 100644
--- a/tests/compiler/dart2js/kernel/impact_test.dart
+++ b/tests/compiler/dart2js/kernel/impact_test.dart
@@ -4,16 +4,17 @@
library dart2js.kernel.impact_test;
-import 'dart:async';
import 'package:async_helper/async_helper.dart';
import 'package:compiler/src/commandline_options.dart';
import 'package:compiler/src/common.dart';
import 'package:compiler/src/common/names.dart';
import 'package:compiler/src/common/resolution.dart';
import 'package:compiler/src/compiler.dart';
+import 'package:compiler/src/constants/expressions.dart';
import 'package:compiler/src/dart_types.dart';
import 'package:compiler/src/elements/elements.dart';
import 'package:compiler/src/resolution/registry.dart';
+import 'package:compiler/src/resolution/tree_elements.dart';
import 'package:compiler/src/ssa/kernel_impact.dart';
import 'package:compiler/src/serialization/equivalence.dart';
import 'package:compiler/src/universe/call_structure.dart';
@@ -26,6 +27,7 @@
const Map<String, String> SOURCE = const <String, String>{
'main.dart': r'''
import 'helper.dart';
+import 'dart:html';
main() {
testEmpty();
@@ -151,6 +153,7 @@
testDefaultValuesNamed();
testFieldInitializer1();
testFieldInitializer2();
+ testFieldInitializer3();
testInstanceFieldWithInitializer();
testInstanceFieldTyped();
testThisInitializer();
@@ -478,6 +481,15 @@
ClassFieldInitializer2(value) : field = value;
}
testFieldInitializer2() => new ClassFieldInitializer2(42);
+class ClassFieldInitializer3 {
+ var field;
+ ClassFieldInitializer3.a();
+ ClassFieldInitializer3.b(value) : field = value;
+}
+testFieldInitializer3() {
+ new ClassFieldInitializer3.a();
+ new ClassFieldInitializer3.b(42);
+}
class ClassInstanceFieldWithInitializer {
var field = false;
}
@@ -603,27 +615,56 @@
compiler.resolution.retainCachesForTesting = true;
await compiler.run(entryPoint);
compiler.libraryLoader.libraries.forEach((LibraryElement library) {
- checkLibrary(compiler, library);
+ checkLibrary(compiler, library, fullTest: args.contains('--full'));
});
});
}
-void checkLibrary(Compiler compiler, LibraryElement library) {
+void checkLibrary(Compiler compiler, LibraryElement library,
+ {bool fullTest: false}) {
library.forEachLocalMember((AstElement element) {
if (element.isClass) {
ClassElement cls = element;
cls.forEachLocalMember((AstElement member) {
- checkElement(compiler, member);
+ checkElement(compiler, member, fullTest: fullTest);
});
} else if (element.isTypedef) {
// Skip typedefs.
} else {
- checkElement(compiler, element);
+ checkElement(compiler, element, fullTest: fullTest);
}
});
}
-void checkElement(Compiler compiler, AstElement element) {
+void checkElement(Compiler compiler, AstElement element,
+ {bool fullTest: false}) {
+ if (!fullTest) {
+ if (element.library.isPlatformLibrary) {
+ // Test only selected elements in web-related platform libraries since
+ // this unittest otherwise takes too long to run.
+ switch (element.library.canonicalUri.path) {
+ case 'html':
+ if ('$element' ==
+ 'function(_ValidatingTreeSanitizer#_sanitizeUntrustedElement)') {
+ break;
+ }
+ return;
+ case 'web_gl':
+ if ('$element' ==
+ 'function(RenderingContext#getFramebufferAttachmentParameter)') {
+ return;
+ }
+ break;
+ case 'indexed_db':
+ if ('$element' == 'field(ObjectStore#keyPath)') {
+ break;
+ }
+ return;
+ case 'web_audio':
+ return;
+ }
+ }
+ }
if (element.isConstructor) {
ConstructorElement constructor = element;
if (constructor.isRedirectingFactory) {
@@ -662,8 +703,8 @@
}
impact.dynamicUses.forEach(builder.registerDynamicUse);
for (TypeUse typeUse in impact.typeUses) {
- builder.registerTypeUse(new TypeUse.internal(
- const Unaliaser().visit(typeUse.type), typeUse.kind));
+ builder.registerTypeUse(
+ new TypeUse.internal(unalias(typeUse.type), typeUse.kind));
}
impact.constantLiterals.forEach(builder.registerConstantLiteral);
impact.constSymbolNames.forEach(builder.registerConstSymbolName);
@@ -671,6 +712,38 @@
impact.mapLiterals.forEach(builder.registerMapLiteral);
for (Feature feature in impact.features) {
switch (feature) {
+ case Feature.FIELD_WITHOUT_INITIALIZER:
+ if (element.isInstanceMember) {
+ bool missing = false;
+ OUTER:
+ for (ConstructorElement constructor
+ in element.enclosingClass.constructors) {
+ if (constructor.isGenerativeConstructor &&
+ !constructor.isRedirectingGenerative) {
+ for (ParameterElement parameter in constructor.parameters) {
+ if (parameter is InitializingFormalElement &&
+ parameter.fieldElement == element) {
+ continue OUTER;
+ }
+ }
+ if (constructor.resolvedAst.kind == ResolvedAstKind.PARSED) {
+ var function = constructor.resolvedAst.node;
+ if (function.initializers != null) {
+ TreeElements elements = constructor.resolvedAst.elements;
+ for (var initializer in function.initializers) {
+ if (elements[initializer] == element) {
+ continue OUTER;
+ }
+ }
+ }
+ }
+ missing = true;
+ }
+ }
+ if (!missing) continue;
+ }
+ builder.registerConstantLiteral(new NullConstantExpression());
+ break;
case Feature.STRING_INTERPOLATION:
case Feature.STRING_JUXTAPOSITION:
// These are both converted into a string concatenation in kernel so
@@ -730,3 +803,8 @@
visitList(type.namedParameterTypes));
}
}
+
+/// Perform unaliasing of all typedefs nested within a [DartType].
+DartType unalias(DartType type) {
+ return const Unaliaser().visit(type);
+}
diff --git a/tests/compiler/dart2js/kernel/visitor_test.dart b/tests/compiler/dart2js/kernel/visitor_test.dart
index 68a6f89..e8ad842 100644
--- a/tests/compiler/dart2js/kernel/visitor_test.dart
+++ b/tests/compiler/dart2js/kernel/visitor_test.dart
@@ -13,6 +13,7 @@
import 'package:kernel/ast.dart';
import 'package:kernel/text/ast_to_text.dart';
import 'package:kernel/transformations/mixin_full_resolution.dart';
+import 'package:kernel/class_hierarchy.dart';
import 'package:path/path.dart' as pathlib;
import 'package:test/test.dart';
@@ -20,7 +21,10 @@
const String TESTCASE_DIR = 'third_party/pkg/kernel/testcases/';
-const List<String> SKIP_TESTS = const <String>[];
+const List<String> SKIP_TESTS = const <String>[
+ // Encoding of redirecting factories have changed.
+ 'redirecting_factory',
+];
main(List<String> arguments) {
Compiler compiler = compilerFor(
diff --git a/tests/corelib/corelib.status b/tests/corelib/corelib.status
index 97426fe..24a5cd6 100644
--- a/tests/corelib/corelib.status
+++ b/tests/corelib/corelib.status
@@ -207,6 +207,3 @@
[ $arch == simdbc || $arch == simdbc64 ]
regexp/stack-overflow_test: RuntimeError, OK # Smaller limit with irregex interpreter
-big_integer_arith_vm_test/gcd: Pass, RuntimeError # Issue #27474
-big_integer_arith_vm_test/modPow: Pass, RuntimeError # Issue #27474
-collection_length_test: Skip # Issue #27746
diff --git a/tests/lib/async/stream_take_test.dart b/tests/lib/async/stream_take_test.dart
new file mode 100644
index 0000000..e341a22
--- /dev/null
+++ b/tests/lib/async/stream_take_test.dart
@@ -0,0 +1,63 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+import "package:expect/expect.dart";
+import "package:async_helper/async_helper.dart";
+
+class A { const A(); }
+class B extends A { const B(); }
+
+/// Stream which emits an error if it's not canceled at the correct time.
+///
+/// Must be canceled after at most [maxEvents] events.
+Stream makeStream(int maxEvents) {
+ var c;
+ int event = 0;
+ bool canceled = false;
+ c = new StreamController(onListen: () {
+ new Timer.periodic(const Duration(milliseconds: 10), (t) {
+ if (canceled) {
+ t.cancel();
+ return;
+ }
+ if (event == maxEvents) {
+ c.addError("NOT CANCELED IN TIME: $maxEvents");
+ c.close();
+ t.cancel();
+ } else {
+ c.add(event++);
+ }
+ });
+ }, onCancel: () {
+ canceled = true;
+ });
+ return c.stream;
+}
+
+main() {
+ asyncStart();
+ tests().then((_) { asyncEnd(); });
+}
+
+tests() async {
+ await expectThrowsAsync(makeStream(4).take(5).toList(), "5/4");
+ await expectThrowsAsync(makeStream(0).take(1).toList(), "1/0");
+
+ Expect.listEquals([0, 1, 2, 3, 4], await makeStream(5).take(5).toList());
+
+ Expect.listEquals([0, 1, 2, 3], await makeStream(5).take(4).toList());
+
+ Expect.listEquals([0], await makeStream(5).take(1).toList());
+
+ Expect.listEquals([], await makeStream(5).take(0).toList());
+
+ Expect.listEquals([], await makeStream(0).take(0).toList());
+}
+
+Future expectThrowsAsync(Future computation, String name) {
+ return computation.then((_) {
+ Expect.fail("$name: Did not throw");
+ }, onError: (e, s){});
+}
diff --git a/tests/lib/lib.status b/tests/lib/lib.status
index 8b3ac69..8d83a13 100644
--- a/tests/lib/lib.status
+++ b/tests/lib/lib.status
@@ -189,6 +189,7 @@
async/stream_controller_test: Fail # Timer interface not supported: Issue 7728.
async/stream_subscription_cancel_test: Fail # Timer interface not supported: Issue 7728.
async/future_constructor2_test: Fail # Timer interface not supported: Issue 7728.
+async/stream_take_test: Fail # Timer interface not supported: Issue 7728.
mirrors/mirrors_reader_test: Skip # Running in v8 suffices. Issue 16589 - RuntimeError. Issue 22130 - Crash (out of memory).
[ $compiler == dart2js && $checked ]
diff --git a/tests/standalone/io/uri_platform_test.dart b/tests/standalone/io/uri_platform_test.dart
index cc67760..45da0e3 100644
--- a/tests/standalone/io/uri_platform_test.dart
+++ b/tests/standalone/io/uri_platform_test.dart
@@ -3,6 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
import "package:expect/expect.dart";
+import 'package:path/path.dart' as path;
import "dart:io";
main() {
@@ -36,7 +37,12 @@
Expect.equals("a/b", new Uri.file("a/b").toFilePath());
Expect.equals("a\\b", new Uri.file("a\\b").toFilePath());
}
-
- Expect.equals(Uri.base,
- new Uri.file(Directory.current.path + Platform.pathSeparator));
+ // If the current path is only the root prefix (/ (or c:\), then don't add a
+ // separator at the end.
+ Expect.equals(
+ Uri.base,
+ (Directory.current.path.toString() !=
+ path.rootPrefix(Directory.current.path.toString()))
+ ? new Uri.file(Directory.current.path + Platform.pathSeparator)
+ : new Uri.file(Directory.current.path));
}
diff --git a/tests/standalone/standalone.status b/tests/standalone/standalone.status
index c8a29f7..85e68b6 100644
--- a/tests/standalone/standalone.status
+++ b/tests/standalone/standalone.status
@@ -329,7 +329,6 @@
[ $compiler == precompiler && $runtime == dart_precompiled && $system == android ]
# Issue 26376
io/file_system_watcher_test: RuntimeError
-io/uri_platform_test: RuntimeError
io/resolve_symbolic_links_test: RuntimeError
io/file_stat_test: RuntimeError
# Issue #27638
diff --git a/tests/utils/utils.status b/tests/utils/utils.status
index 6ad1ebf..fde7eba 100644
--- a/tests/utils/utils.status
+++ b/tests/utils/utils.status
@@ -25,7 +25,7 @@
recursive_import_test: Skip # Running dart2js under frequent reloads is slow.
dummy_compiler_test: Skip # Running dart2js under frequent reloads is slow.
-[ $runtime == dartium ]
+[ $compiler == none && ($runtime == dartium || $runtime == drt) ]
dummy_compiler_test: Skip # Issue 27744
recursive_import_test: Skip # Issue 27744
diff --git a/tools/VERSION b/tools/VERSION
index 0993f30..bbdce97 100644
--- a/tools/VERSION
+++ b/tools/VERSION
@@ -28,5 +28,5 @@
MAJOR 1
MINOR 21
PATCH 0
-PRERELEASE 4
+PRERELEASE 5
PRERELEASE_PATCH 0
diff --git a/tools/gn.py b/tools/gn.py
index 1ee3d33..0a385f3 100755
--- a/tools/gn.py
+++ b/tools/gn.py
@@ -113,11 +113,15 @@
gn_args['is_asan'] = args.asan and gn_args['is_clang']
- if args.target_sysroot:
- gn_args['target_sysroot'] = args.target_sysroot
+ # Setup the user-defined sysroot.
+ if gn_args['target_os'] == 'linux' and args.wheezy:
+ gn_args['dart_use_wheezy_sysroot'] = True
+ else:
+ if args.target_sysroot:
+ gn_args['target_sysroot'] = args.target_sysroot
- if args.toolchain_prefix:
- gn_args['toolchain_prefix'] = args.toolchain_prefix
+ if args.toolchain_prefix:
+ gn_args['toolchain_prefix'] = args.toolchain_prefix
goma_dir = os.environ.get('GOMA_DIR')
goma_home_dir = os.path.join(os.getenv('HOME', ''), 'goma')
@@ -195,6 +199,18 @@
return '--ide=json'
+# Environment variables for default settings.
+DART_USE_ASAN = "DART_USE_ASAN"
+DART_USE_WHEEZY = "DART_USE_WHEEZY"
+
+def use_asan():
+ return DART_USE_ASAN in os.environ
+
+
+def use_wheezy():
+ return DART_USE_WHEEZY in os.environ
+
+
def parse_args(args):
args = args[1:]
parser = argparse.ArgumentParser(description='A script to run `gn gen`.')
@@ -220,8 +236,20 @@
default='x64')
parser.add_argument('--asan',
help='Build with ASAN',
- default=False,
+ default=use_asan(),
action='store_true')
+ parser.add_argument('--no-asan',
+ help='Disable ASAN',
+ dest='asan',
+ action='store_false')
+ parser.add_argument('--wheezy',
+ help='Use the Debian wheezy sysroot on Linux',
+ default=use_wheezy(),
+ action='store_true')
+ parser.add_argument('--no-wheezy',
+ help='Disable the Debian wheezy sysroot on Linux',
+ dest='wheezy',
+ action='store_false')
parser.add_argument('--goma',
help='Use goma',
default=True,