Compare commits

...

39 Commits

Author SHA1 Message Date
trop[bot]
9ec710e99c fix: WCO maximize button visibility when non-maximizable (#41806)
fix: WCO button visibility when non-maximizable

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2024-04-09 19:57:48 -04:00
Pedro Pontes
e9060c2793 chore: cherry-pick 1 change from Release-2-M123 (#41776) 2024-04-05 13:55:03 -04:00
Milan Burda
03bfd50875 feat: add support for configuring system network context proxies (#41744)
feat: add support for configuring system network context proxies (#41335)
2024-04-03 13:09:44 -04:00
trop[bot]
484b75568f fix: Storage.{get|set|clear}Cookies via CDP not working (#41738)
* fix: Storage.{get|set|clear}Cookies via CDP not working

Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>

* chore: simplify BrowserContext plumbing

Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>

---------

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2024-04-02 11:31:02 +02:00
trop[bot]
2e95cf50bb docs: add missing headers option to ClientRequest options (#41731)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
2024-04-01 12:06:09 -04:00
Pedro Pontes
c29526b721 chore: cherry-pick 8 changes from Release-1-M123 (#41747)
* chore: cherry-pick 8 changes from Release-1-M123

* chore: update patches

---------

Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com>
2024-04-01 11:42:38 -04:00
trop[bot]
f4b7aa5401 fix: don't do self-destroy in LibnotifyNotification::Dismiss() (#41709)
Callers of Notification::Dismiss() assume that the notification
instance is not deleted after the call, but this was not the case
for LibnotifyNotification:
- Destroy() would get `this` deleted.
- notify_notification_close() in portal environment triggers
LibnotifyNotification::OnNotificationClosed(), and finally calls
Destroy()

This patch removes all Destroy() in Dismiss(), and adds a boolean
to tell whether notify_notification_close() is running, to avoid crash
under portal environment.

Fixes #40461.

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: taoky <me@taoky.moe>
2024-03-28 20:50:04 -05:00
trop[bot]
76172fd27e fix: normalize path before calling showItemInFolder and openPath (#41670)
* fix: normalize path before calling ShowItemInFolder

Co-authored-by: piotrpdev <piotrpdev@gmail.com>

* fix: normalize path before calling OpenPath

Co-authored-by: piotrpdev <piotrpdev@gmail.com>

---------

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: piotrpdev <piotrpdev@gmail.com>
2024-03-25 11:15:05 +01:00
John Kleinschmidt
c145388dd2 ci: use CircleCI hosted macOS arm64 runners for testing (#41658)
* ci: use CircleCI hosted macOS arm64 runners for testing

(cherry picked from commit 6ca2aa6b06)

* ci: Use same version of xcode/macOS for both arm and x64 testing
2024-03-22 08:59:47 -04:00
trop[bot]
faa3dc7654 docs: nodejs trademark policy link broken (#41651)
* Fix broken Trademark Policy link

Co-authored-by: kghamilton89 <kghamilton@protonmail.com>

* add durable link

Per codebyter: https://github.com/electron/electron/pull/41558#discussion_r1522938560

Co-authored-by: Kenneth Gerald Hamilton <29099829+kghamilton89@users.noreply.github.com>

---------

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: kghamilton89 <kghamilton@protonmail.com>
Co-authored-by: Kenneth Gerald Hamilton <29099829+kghamilton89@users.noreply.github.com>
2024-03-21 13:30:04 -04:00
Pedro Pontes
3f0dd063cb chore: cherry-pick 1 change from Release-0-M123 (#41632) 2024-03-21 09:42:58 -04:00
trop[bot]
c2184ad4ff fix: serial-port-added should respect filters (#41637)
fix: serial-port-added should respect filters

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2024-03-21 09:39:13 -04:00
Pedro Pontes
31cd9d1f61 chore: cherry-pick 1 change from Release-3-M122 (#41607) 2024-03-18 10:49:04 +01:00
trop[bot]
ca6bd89a69 fix: account for potentially swapped FrameTreeNodeId in WebFrameMain (#41592)
fix: account for potentially swapped `FrameTreeNodeId` in `WebFrameMain` (#41538)

fix: account for potentially swapped FrameTreeNodeId in WebFrameMain

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2024-03-14 10:59:06 -04:00
Pedro Pontes
82b648e491 chore: cherry-pick 1 change from Release-2-M122 (#41520) 2024-03-07 13:09:49 -05:00
trop[bot]
085363db07 fix: chrome://process-internals failing to load (#41541)
fix: chrome://process-internals failing to load

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2024-03-07 13:09:09 -05:00
trop[bot]
565988c96f fix: user-did-{resign|become}-active events on macOS (#41526)
fix: user-did-{resign|become}-active events on macOS

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2024-03-06 11:02:54 -05:00
trop[bot]
2977fc4025 chore: add missing gin::Wrappable GetTypeName overrides (#41529)
chore: add missing gin::Wrappable GetTypeName overrides

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2024-03-06 15:57:56 +01:00
Cheng Zhao
1ded991603 chore: update src_preload_function_for_environment.patch (#41502)
* chore: update src_preload_function_for_environment.patch

* chore: update patches

---------

Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com>
2024-03-04 10:25:06 -05:00
Pedro Pontes
dc19cd2c9d chore: cherry-pick 1 change from Release-1-M122 (#41487)
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
2024-03-04 16:46:12 +09:00
trop[bot]
945f1c7262 fix: webContents.print options should be optional (#41478)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2024-03-01 17:11:10 -05:00
Robo
70255b1db1 fix: saving traces from devtools performance panel (#41492) 2024-03-01 16:51:29 -05:00
Shelley Vohr
c96d7db592 fix: node::loader::ImportModuleDynamically crash (#41491)
* fix: node::loader::ImportModuleDynamically crash

* chore: add regression test
2024-03-01 15:51:51 -05:00
trop[bot]
6780e671f9 chore: fix import from patches.py in script/lib/git.py (#41434)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Milan Burda <milan.burda@gmail.com>
2024-02-29 09:54:55 -06:00
trop[bot]
e5799c1dc2 ci: add logging to uploading to GitHub releases (#41456)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
2024-02-29 10:00:48 +01:00
Pedro Pontes
6544cec686 chore: cherry-pick 1 change from Release-0-M122 (#41405) 2024-02-22 14:31:22 +01:00
Pedro Pontes
8618d5d220 chore: cherry-pick 1 change from Release-3-M121 (#41374) 2024-02-21 09:43:43 +01:00
trop[bot]
15d87d48b2 fix: Ignore -webkit-app-region: drag; when window is in full screen mode. (#41330)
fix: Ignore `-webkit-app-region: drag;` when window is in full screen mode. (#41307)

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Mikhail Leliakin <leliakin@canva.com>
2024-02-16 14:59:08 -05:00
electron-roller[bot]
59436b032b chore: bump chromium to 120.0.6099.291 (28-x-y) (#41334)
chore: bump chromium in DEPS to 120.0.6099.291

Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com>
2024-02-16 14:58:57 -05:00
Charles Kerr
e93a028c91 chore: migrate base::StringPiece to std::string_view (#40915) (#41345)
chore: migrate base::StringPiece to std::string_view (#40915) (#40973)

* chore: migrate from base::StringPiece to std::string_view in keyboard_util.cc

* chore: migrate from base::StringPiece to std::string_view in error_thrower.cc

* chore: migrate from base::StringPiece to std::string_view in electron_api_web_contents.cc

* chore: migrate from base::StringPiece to std::string_view in gin_helper/dictionary.h

* chore: migrate from base::StringPiece to std::string_view in electron_api_url_loader.cc

* chore: phase out internal use of base:::StringPiece

`base::StringPiece` is being phased out upstream. Its code has been
removed upstream and it's just a typedef for `std::string_view`.

They haven't removed the typedef yet, so this PR tries to get ahead
of future breakage by migrating "internal" use (i.e. leaving alone the
places where the `base::StringPiece` name is coming from an upstream
method that we override).

Xref: https://bugs.chromium.org/p/chromium/issues/detail?id=691162

Xref: https://chromium-review.googlesource.com/c/chromium/src/+/4294483

Xref: https://docs.google.com/document/d/1d4RnD1uAE2t4iANR0nXy82ASIPGsPuw2mpO6v6T7JKs
2024-02-15 11:01:16 -05:00
John Kleinschmidt
80de0b6acd build: peg to a specific depot_tools so that we can use goma on older branches (#41336)
chore: peg to a specific depot_tools so that we can use goma on older branches
2024-02-14 13:35:26 -05:00
Charles Kerr
28485340b0 build: allow custom refs for patch import & export (#41317)
feat: allow custom refs for patch import & export (#41306)

* feat: allow custom refs for patch import & export

feat: add Patch-Dir metainfo, a sibling to Patch-Filename

* chore: copyediting

* refactor: minor copyediting
2024-02-12 23:11:28 +01:00
trop[bot]
de85def21b fix: destroy NodeService message pipe last (#41302)
refactor: destroy NodeService message pipe last

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2024-02-11 22:25:45 +01:00
trop[bot]
c9ff1d38e4 fix: crash on macOS non-programmatic close (#41298)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2024-02-11 21:14:55 +01:00
Charles Kerr
3649df1043 build: export matching patches (#41292) 2024-02-09 17:29:28 -06:00
electron-roller[bot]
89817d6a02 chore: bump chromium to 120.0.6099.283 (28-x-y) (#41262)
chore: bump chromium in DEPS to 120.0.6099.283

Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com>
2024-02-09 22:44:49 +01:00
trop[bot]
8177a16f9a docs: note EXIF data unsupported in nativeImage (#41283)
* docs: note EXIF data unsupported in nativeImage

Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>

* Update docs/api/native-image.md

Co-authored-by: David Sanders <dsanders11@ucsbalum.com>

Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>

---------

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2024-02-08 11:57:44 -06:00
Shelley Vohr
abd7850ee4 fix: validate printToPDF margins against pageSize (#41267) 2024-02-08 11:15:42 +09:00
Shelley Vohr
b0c3534ecb fix: webview zoom level persistence on navigation (#41268) 2024-02-08 11:15:19 +09:00
131 changed files with 5132 additions and 642 deletions

View File

@@ -75,10 +75,6 @@ executors:
resource_class: << parameters.size >>
# Electron Runners
apple-silicon:
resource_class: electronjs/macos-arm64
machine: true
linux-arm:
resource_class: electronjs/aks-linux-arm-test
docker:
@@ -252,6 +248,10 @@ step-depot-tools-get: &step-depot-tools-get
name: Get depot tools
command: |
git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git
cd depot_tools
git fetch --depth 1 origin f76550541c751f956ef9287f2695a6c8a74bf709
git checkout f76550541c751f956ef9287f2695a6c8a74bf709
cd ..
if [ "`uname`" == "Darwin" ]; then
# remove ninjalog_uploader_wrapper.py from autoninja since we don't use it and it causes problems
sed -i '' '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja
@@ -2327,8 +2327,11 @@ jobs:
- electron-tests:
artifact-key: darwin-x64
darwin-testing-arm64-tests:
executor: apple-silicon
darwin-testing-arm64-tests:
executor:
name: macos
size: macos.m1.medium.gen1
version: 14.0.0
environment:
<<: *env-mac-large
<<: *env-stack-dumping
@@ -2352,7 +2355,10 @@ jobs:
artifact-key: mas-x64
mas-testing-arm64-tests:
executor: apple-silicon
executor:
name: macos
size: macos.m1.medium.gen1
version: 14.0.0
environment:
<<: *env-mac-large
<<: *env-stack-dumping

2
DEPS
View File

@@ -2,7 +2,7 @@ gclient_gn_args_from = 'src'
vars = {
'chromium_version':
'120.0.6099.276',
'120.0.6099.291',
'node_version':
'v18.18.2',
'nan_version':

View File

@@ -112,4 +112,4 @@ and more can be found on the [Community page](https://www.electronjs.org/communi
[MIT](https://github.com/electron/electron/blob/main/LICENSE)
When using Electron logos, make sure to follow [OpenJS Foundation Trademark Policy](https://openjsf.org/wp-content/uploads/sites/84/2021/01/OpenJS-Foundation-Trademark-Policy-2021-01-12.docx.pdf).
When using Electron logos, make sure to follow [OpenJS Foundation Trademark Policy](https://trademark-policy.openjsf.org/).

View File

@@ -94,6 +94,11 @@ for:
Remove-Item -Recurse -Force $pwd\build-tools
}
- git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git
- ps: |
cd depot_tools
git fetch --depth 1 origin f76550541c751f956ef9287f2695a6c8a74bf709
git checkout f76550541c751f956ef9287f2695a6c8a74bf709
cd ..
- ps: New-Item -Name depot_tools\.disable_auto_update -ItemType File
- depot_tools\bootstrap\win_tools.bat
- ps: $env:PATH="$pwd\depot_tools;$env:PATH"

View File

@@ -92,6 +92,11 @@ for:
Remove-Item -Recurse -Force $pwd\build-tools
}
- git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git
- ps: |
cd depot_tools
git fetch --depth 1 origin f76550541c751f956ef9287f2695a6c8a74bf709
git checkout f76550541c751f956ef9287f2695a6c8a74bf709
cd ..
- ps: New-Item -Name depot_tools\.disable_auto_update -ItemType File
- depot_tools\bootstrap\win_tools.bat
- ps: $env:PATH="$pwd\depot_tools;$env:PATH"

View File

@@ -1496,6 +1496,24 @@ details.
**Note:** Enable `Secure Keyboard Entry` only when it is needed and disable it when it is no longer needed.
### `app.setProxy(config)`
* `config` [ProxyConfig](structures/proxy-config.md)
Returns `Promise<void>` - Resolves when the proxy setting process is complete.
Sets the proxy settings for networks requests made without an associated [Session](session.md).
Currently this will affect requests made with [Net](net.md) in the [utility process](../glossary.md#utility-process)
and internal requests made by the runtime (ex: geolocation queries).
This method can only be called after app is ready.
#### `app.resolveProxy(url)`
* `url` URL
Returns `Promise<string>` - Resolves with the proxy information for `url` that will be used when attempting to make requests using [Net](net.md) in the [utility process](../glossary.md#utility-process).
## Properties
### `app.accessibilitySupportEnabled` _macOS_ _Windows_

View File

@@ -17,6 +17,8 @@ following properties:
method.
* `url` string (optional) - The request URL. Must be provided in the absolute
form with the protocol scheme specified as http or https.
* `headers` Record<string, string | string[]> (optional) - Headers to be sent
with the request.
* `session` Session (optional) - The [`Session`](session.md) instance with
which the request is associated.
* `partition` string (optional) - The name of the [`partition`](session.md)

View File

@@ -51,6 +51,13 @@ Check the _Size requirements_ section in [this article][icons].
[icons]: https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-icons
:::note
EXIF metadata is currently not supported and will not be taken into account during
image encoding and decoding.
:::
## High Resolution Image
On platforms that have high-DPI support such as Apple Retina displays, you can

View File

@@ -589,105 +589,15 @@ Writes any unwritten DOMStorage data to disk.
#### `ses.setProxy(config)`
* `config` Object
* `mode` string (optional) - The proxy mode. Should be one of `direct`,
`auto_detect`, `pac_script`, `fixed_servers` or `system`. If it's
unspecified, it will be automatically determined based on other specified
options.
* `direct`
In direct mode all connections are created directly, without any proxy involved.
* `auto_detect`
In auto_detect mode the proxy configuration is determined by a PAC script that can
be downloaded at http://wpad/wpad.dat.
* `pac_script`
In pac_script mode the proxy configuration is determined by a PAC script that is
retrieved from the URL specified in the `pacScript`. This is the default mode
if `pacScript` is specified.
* `fixed_servers`
In fixed_servers mode the proxy configuration is specified in `proxyRules`.
This is the default mode if `proxyRules` is specified.
* `system`
In system mode the proxy configuration is taken from the operating system.
Note that the system mode is different from setting no proxy configuration.
In the latter case, Electron falls back to the system settings
only if no command-line options influence the proxy configuration.
* `pacScript` string (optional) - The URL associated with the PAC file.
* `proxyRules` string (optional) - Rules indicating which proxies to use.
* `proxyBypassRules` string (optional) - Rules indicating which URLs should
bypass the proxy settings.
* `config` [ProxyConfig](structures/proxy-config.md)
Returns `Promise<void>` - Resolves when the proxy setting process is complete.
Sets the proxy settings.
When `mode` is unspecified, `pacScript` and `proxyRules` are provided together, the `proxyRules`
option is ignored and `pacScript` configuration is applied.
You may need `ses.closeAllConnections` to close currently in flight connections to prevent
pooled sockets using previous proxy from being reused by future requests.
The `proxyRules` has to follow the rules below:
```sh
proxyRules = schemeProxies[";"<schemeProxies>]
schemeProxies = [<urlScheme>"="]<proxyURIList>
urlScheme = "http" | "https" | "ftp" | "socks"
proxyURIList = <proxyURL>[","<proxyURIList>]
proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>]
```
For example:
* `http=foopy:80;ftp=foopy2` - Use HTTP proxy `foopy:80` for `http://` URLs, and
HTTP proxy `foopy2:80` for `ftp://` URLs.
* `foopy:80` - Use HTTP proxy `foopy:80` for all URLs.
* `foopy:80,bar,direct://` - Use HTTP proxy `foopy:80` for all URLs, failing
over to `bar` if `foopy:80` is unavailable, and after that using no proxy.
* `socks4://foopy` - Use SOCKS v4 proxy `foopy:1080` for all URLs.
* `http=foopy,socks5://bar.com` - Use HTTP proxy `foopy` for http URLs, and fail
over to the SOCKS5 proxy `bar.com` if `foopy` is unavailable.
* `http=foopy,direct://` - Use HTTP proxy `foopy` for http URLs, and use no
proxy if `foopy` is unavailable.
* `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use
`socks4://foopy2` for all other URLs.
The `proxyBypassRules` is a comma separated list of rules described below:
* `[ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ]`
Match all hostnames that match the pattern HOSTNAME_PATTERN.
Examples:
"foobar.com", "\*foobar.com", "\*.foobar.com", "\*foobar.com:99",
"https://x.\*.y.com:99"
* `"." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ]`
Match a particular domain suffix.
Examples:
".google.com", ".com", "http://.google.com"
* `[ SCHEME "://" ] IP_LITERAL [ ":" PORT ]`
Match URLs which are IP address literals.
Examples:
"127.0.1", "\[0:0::1]", "\[::1]", "http://\[::1]:99"
* `IP_LITERAL "/" PREFIX_LENGTH_IN_BITS`
Match any URL that is to an IP literal that falls between the
given range. IP range is specified using CIDR notation.
Examples:
"192.168.1.1/16", "fefe:13::abc/33".
* `<local>`
Match local addresses. The meaning of `<local>` is whether the
host matches one of: "127.0.0.1", "::1", "localhost".
#### `ses.resolveHost(host, [options])`
* `host` string - Hostname to resolve.

View File

@@ -0,0 +1,86 @@
# ProxyConfig Object
* `mode` string (optional) - The proxy mode. Should be one of `direct`,
`auto_detect`, `pac_script`, `fixed_servers` or `system`.
Defaults to `pac_script` proxy mode if `pacScript` option is specified
otherwise defaults to `fixed_servers`.
* `direct` - In direct mode all connections are created directly, without any proxy involved.
* `auto_detect` - In auto_detect mode the proxy configuration is determined by a PAC script that can
be downloaded at http://wpad/wpad.dat.
* `pac_script` - In pac_script mode the proxy configuration is determined by a PAC script that is
retrieved from the URL specified in the `pacScript`. This is the default mode if `pacScript` is specified.
* `fixed_servers` - In fixed_servers mode the proxy configuration is specified in `proxyRules`.
This is the default mode if `proxyRules` is specified.
* `system` - In system mode the proxy configuration is taken from the operating system.
Note that the system mode is different from setting no proxy configuration.
In the latter case, Electron falls back to the system settings only if no
command-line options influence the proxy configuration.
* `pacScript` string (optional) - The URL associated with the PAC file.
* `proxyRules` string (optional) - Rules indicating which proxies to use.
* `proxyBypassRules` string (optional) - Rules indicating which URLs should
bypass the proxy settings.
When `mode` is unspecified, `pacScript` and `proxyRules` are provided together, the `proxyRules`
option is ignored and `pacScript` configuration is applied.
The `proxyRules` has to follow the rules below:
```sh
proxyRules = schemeProxies[";"<schemeProxies>]
schemeProxies = [<urlScheme>"="]<proxyURIList>
urlScheme = "http" | "https" | "ftp" | "socks"
proxyURIList = <proxyURL>[","<proxyURIList>]
proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>]
```
For example:
* `http=foopy:80;ftp=foopy2` - Use HTTP proxy `foopy:80` for `http://` URLs, and
HTTP proxy `foopy2:80` for `ftp://` URLs.
* `foopy:80` - Use HTTP proxy `foopy:80` for all URLs.
* `foopy:80,bar,direct://` - Use HTTP proxy `foopy:80` for all URLs, failing
over to `bar` if `foopy:80` is unavailable, and after that using no proxy.
* `socks4://foopy` - Use SOCKS v4 proxy `foopy:1080` for all URLs.
* `http=foopy,socks5://bar.com` - Use HTTP proxy `foopy` for http URLs, and fail
over to the SOCKS5 proxy `bar.com` if `foopy` is unavailable.
* `http=foopy,direct://` - Use HTTP proxy `foopy` for http URLs, and use no
proxy if `foopy` is unavailable.
* `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use
`socks4://foopy2` for all other URLs.
The `proxyBypassRules` is a comma separated list of rules described below:
* `[ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ]`
Match all hostnames that match the pattern HOSTNAME_PATTERN.
Examples:
"foobar.com", "\*foobar.com", "\*.foobar.com", "\*foobar.com:99",
"https://x.\*.y.com:99"
* `"." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ]`
Match a particular domain suffix.
Examples:
".google.com", ".com", "http://.google.com"
* `[ SCHEME "://" ] IP_LITERAL [ ":" PORT ]`
Match URLs which are IP address literals.
Examples:
"127.0.1", "\[0:0::1]", "\[::1]", "http://\[::1]:99"
* `IP_LITERAL "/" PREFIX_LENGTH_IN_BITS`
Match any URL that is to an IP literal that falls between the
given range. IP range is specified using CIDR notation.
Examples:
"192.168.1.1/16", "fefe:13::abc/33".
* `<local>`
Match local addresses. The meaning of `<local>` is whether the
host matches one of: "127.0.0.1", "::1", "localhost".

View File

@@ -77,6 +77,7 @@ template("electron_extra_paks") {
"//content:content_resources",
"//content/browser/resources/gpu:resources",
"//content/browser/resources/media:resources",
"//content/browser/resources/process:resources",
"//content/browser/tracing:resources",
"//content/browser/webrtc/resources",
"//electron:resources",
@@ -96,6 +97,7 @@ template("electron_extra_paks") {
# New paks should be added here by default.
sources += [
"$root_gen_dir/content/browser/devtools/devtools_resources.pak",
"$root_gen_dir/content/process_resources.pak",
"$root_gen_dir/ui/resources/webui_resources.pak",
]
deps += [ "//content/browser/devtools:devtools_resources" ]

View File

@@ -113,6 +113,7 @@ auto_filenames = {
"docs/api/structures/protocol-request.md",
"docs/api/structures/protocol-response-upload-data.md",
"docs/api/structures/protocol-response.md",
"docs/api/structures/proxy-config.md",
"docs/api/structures/rectangle.md",
"docs/api/structures/referrer.md",
"docs/api/structures/render-process-gone-details.md",

View File

@@ -220,6 +220,16 @@ function parsePageSize (pageSize: string | ElectronInternal.PageSize) {
let pendingPromise: Promise<any> | undefined;
WebContents.prototype.printToPDF = async function (options) {
const margins = checkType(options.margins ?? {}, 'object', 'margins');
const pageSize = parsePageSize(options.pageSize ?? 'letter');
const { top, bottom, left, right } = margins;
const validHeight = [top, bottom].every(u => u === undefined || u <= pageSize.paperHeight);
const validWidth = [left, right].every(u => u === undefined || u <= pageSize.paperWidth);
if (!validHeight || !validWidth) {
throw new Error('margins must be less than or equal to pageSize');
}
const printSettings = {
requestID: getNextId(),
landscape: checkType(options.landscape ?? false, 'boolean', 'landscape'),
@@ -235,7 +245,7 @@ WebContents.prototype.printToPDF = async function (options) {
pageRanges: checkType(options.pageRanges ?? '', 'string', 'pageRanges'),
preferCSSPageSize: checkType(options.preferCSSPageSize ?? false, 'boolean', 'preferCSSPageSize'),
generateTaggedPDF: checkType(options.generateTaggedPDF ?? false, 'boolean', 'generateTaggedPDF'),
...parsePageSize(options.pageSize ?? 'letter')
...pageSize
};
if (this._printToPDF) {
@@ -252,13 +262,11 @@ WebContents.prototype.printToPDF = async function (options) {
// TODO(codebytere): deduplicate argument sanitization by moving rest of
// print param logic into new file shared between printToPDF and print
WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions, callback) {
if (typeof options !== 'object') {
WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions = {}, callback) {
if (typeof options !== 'object' || options == null) {
throw new TypeError('webContents.print(): Invalid print settings specified.');
}
const printSettings: Record<string, any> = { ...options };
const pageSize = options.pageSize ?? 'A4';
if (typeof pageSize === 'object') {
if (!pageSize.height || !pageSize.width) {
@@ -272,7 +280,7 @@ WebContents.prototype.print = function (options: ElectronInternal.WebContentsPri
throw new RangeError('height and width properties must be minimum 352 microns.');
}
printSettings.mediaSize = {
options.mediaSize = {
name: 'CUSTOM',
custom_display_name: 'Custom',
height_microns: height,
@@ -284,7 +292,7 @@ WebContents.prototype.print = function (options: ElectronInternal.WebContentsPri
};
} else if (typeof pageSize === 'string' && PDFPageSizes[pageSize]) {
const mediaSize = PDFPageSizes[pageSize];
printSettings.mediaSize = {
options.mediaSize = {
...mediaSize,
imageable_area_left_microns: 0,
imageable_area_bottom_microns: 0,
@@ -297,9 +305,9 @@ WebContents.prototype.print = function (options: ElectronInternal.WebContentsPri
if (this._print) {
if (callback) {
this._print(printSettings, callback);
this._print(options, callback);
} else {
this._print(printSettings);
this._print(options);
}
} else {
console.error('Error: Printing feature is disabled.');

1
patches/angle/.patches Normal file
View File

@@ -0,0 +1 @@
m123_vulkan_fix_access_to_inactive_attributes.patch

View File

@@ -0,0 +1,112 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Geoff Lang <geofflang@chromium.org>
Date: Tue, 12 Mar 2024 16:06:37 -0400
Subject: M123: Vulkan: Fix access to inactive attributes
... within range of active ones. Since a buffer is bound for inactive
attributes, it must be considered accessed.
Ultimately, the nullDescriptor feature could be used to avoid binding a
buffer for inactive attributes.
Bug: chromium:327807820
Change-Id: I953b419d8ec51760e8848409024cad5083888fa2
Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/5386431
Reviewed-by: Shahbaz Youssefi <syoussefi@google.com>
diff --git a/src/libANGLE/renderer/vulkan/ContextVk.cpp b/src/libANGLE/renderer/vulkan/ContextVk.cpp
index 4849b95b25309a191e45a7eb39bb114ebc7376b1..a37e2865f9d49f576cec39845b66f3a0bdfd1652 100644
--- a/src/libANGLE/renderer/vulkan/ContextVk.cpp
+++ b/src/libANGLE/renderer/vulkan/ContextVk.cpp
@@ -2607,8 +2607,7 @@ angle::Result ContextVk::handleDirtyGraphicsVertexBuffers(DirtyBits::Iterator *d
vertexArrayVk->getCurrentArrayBuffers();
// Mark all active vertex buffers as accessed.
- const gl::AttributesMask attribsMask = executable->getActiveAttribLocationsMask();
- for (size_t attribIndex : attribsMask)
+ for (uint32_t attribIndex = 0; attribIndex < maxAttrib; ++attribIndex)
{
vk::BufferHelper *arrayBuffer = arrayBufferResources[attribIndex];
if (arrayBuffer)
diff --git a/src/tests/gl_tests/VertexAttributeTest.cpp b/src/tests/gl_tests/VertexAttributeTest.cpp
index 010662aded3f22a487230c24de1cda9de42cc334..a51322ee27309c8aeb146b1288099a68b258386f 100644
--- a/src/tests/gl_tests/VertexAttributeTest.cpp
+++ b/src/tests/gl_tests/VertexAttributeTest.cpp
@@ -1200,6 +1200,19 @@ class VertexAttributeOORTest : public VertexAttributeTest
}
};
+class RobustVertexAttributeTest : public VertexAttributeTest
+{
+ public:
+ RobustVertexAttributeTest()
+ {
+ // mac GL and metal do not support robustness.
+ if (!IsMac() && !IsIOS())
+ {
+ setRobustAccess(true);
+ }
+ }
+};
+
// Verify that drawing with a large out-of-range offset generates INVALID_OPERATION.
// Requires WebGL compatibility with robust access behaviour disabled.
TEST_P(VertexAttributeOORTest, ANGLEDrawArraysBufferTooSmall)
@@ -1260,6 +1273,48 @@ TEST_P(VertexAttributeOORTest, ANGLEDrawArraysOutOfBoundsCases)
EXPECT_GL_ERROR(GL_INVALID_OPERATION);
}
+// Test that enabling a buffer in an unused attribute doesn't crash. There should be an active
+// attribute after that.
+TEST_P(RobustVertexAttributeTest, BoundButUnusedBuffer)
+{
+ constexpr char kVS[] = R"(attribute vec2 offset;
+void main()
+{
+ gl_Position = vec4(offset.xy, 0, 1);
+ gl_PointSize = 1.0;
+})";
+
+ constexpr char kFS[] = R"(precision mediump float;
+void main()
+{
+ gl_FragColor = vec4(1.0, 0, 0, 1.0);
+})";
+
+ const GLuint vs = CompileShader(GL_VERTEX_SHADER, kVS);
+ const GLuint fs = CompileShader(GL_FRAGMENT_SHADER, kFS);
+
+ GLuint program = glCreateProgram();
+ glBindAttribLocation(program, 1, "offset");
+ glAttachShader(program, vs);
+ glAttachShader(program, fs);
+ glLinkProgram(program);
+
+ GLBuffer buffer;
+ glBindBuffer(GL_ARRAY_BUFFER, buffer);
+ glBufferData(GL_ARRAY_BUFFER, 100, nullptr, GL_STATIC_DRAW);
+
+ // Enable an unused attribute that is within the range of active attributes (not beyond it)
+ glEnableVertexAttribArray(0);
+ glVertexAttribPointer(0, 4, GL_FLOAT, false, 0, 0);
+
+ glUseProgram(program);
+ glDrawArrays(GL_TRIANGLES, 0, 6);
+
+ // Destroy the buffer. Regression test for a tracking bug where the buffer was used by
+ // SwiftShader (even though location 1 is inactive), but not marked as used by ANGLE.
+ buffer.reset();
+}
+
// Verify that using a different start vertex doesn't mess up the draw.
TEST_P(VertexAttributeTest, DrawArraysWithBufferOffset)
{
@@ -4739,6 +4794,8 @@ ANGLE_INSTANTIATE_TEST_ES2_AND_ES3_AND(
ES3_METAL().disable(Feature::HasExplicitMemBarrier).disable(Feature::HasCheapRenderPass),
ES3_METAL().disable(Feature::HasExplicitMemBarrier).enable(Feature::HasCheapRenderPass));
+ANGLE_INSTANTIATE_TEST_ES2_AND_ES3(RobustVertexAttributeTest);
+
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(VertexAttributeTestES3);
ANGLE_INSTANTIATE_TEST_ES3_AND(
VertexAttributeTestES3,

View File

@@ -144,3 +144,10 @@ feat_allow_code_cache_in_custom_schemes.patch
enable_partition_alloc_ref_count_size.patch
ensure_an_axcontext_before_painting.patch
safely_crash_on_dangling_profile.patch
prevent_mojotrap_event_re-ordering.patch
m122_cherry_pick_cve-2024-25062_libxml_fix.patch
allowlist_devtools_for_file_access_permission.patch
update_crashpad_to_37afd37401253ebcebcf6e07ce15c8cfecb1a1cc.patch
m122_webcodecs_disable_async_videoframe_readback_to_mitigate_a.patch
fix_paintimage_deserialization_arbitrary-read_issue.patch
reland_sensors_winrt_call_onreadingchangedcallback_via.patch

View File

@@ -0,0 +1,61 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Yang Guo <yangguo@chromium.org>
Date: Tue, 19 Dec 2023 19:34:20 +0000
Subject: Allowlist devtools:// for file access permission
Otherwise DevTools features which save logs to the filesystem are
affected by content permissions, which contradicts developer
expectations.
Fixed: 1483230
Change-Id: Ia0848a9a192b2803a64f4104f4032219d6f3a885
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5132146
Auto-Submit: Yang Guo <yangguo@chromium.org>
Reviewed-by: Christian Dullweber <dullweber@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1239281}
diff --git a/chrome/browser/content_settings/host_content_settings_map_unittest.cc b/chrome/browser/content_settings/host_content_settings_map_unittest.cc
index 38464529cc74e7b17373e1dd4f7bfd8cc68ff796..99323d6453749edd98f0cace905e9c5312620825 100644
--- a/chrome/browser/content_settings/host_content_settings_map_unittest.cc
+++ b/chrome/browser/content_settings/host_content_settings_map_unittest.cc
@@ -2354,3 +2354,26 @@ TEST_F(HostContentSettingsMapTest, IncognitoInheritSaaAndRenew) {
ContentSetting::CONTENT_SETTING_ALLOW);
EXPECT_EQ(CONTENT_SETTING_ASK, otr_map->GetContentSetting(host, host, type));
}
+
+// File access is not implemented on Android. Luckily we don't need it for DevTools.
+#if !BUILDFLAG(IS_ANDROID)
+TEST_F(HostContentSettingsMapTest, DevToolsFileAccess) {
+ TestingProfile profile;
+ HostContentSettingsMap* host_content_settings_map =
+ HostContentSettingsMapFactory::GetForProfile(&profile);
+
+ GURL devtools_host("devtools://devtools/bundled/devtools_app.html");
+ GURL example_host("https://example.com");
+
+ host_content_settings_map->SetDefaultContentSetting(
+ ContentSettingsType::FILE_SYSTEM_WRITE_GUARD, CONTENT_SETTING_BLOCK);
+ EXPECT_EQ(CONTENT_SETTING_ALLOW,
+ host_content_settings_map->GetContentSetting(
+ devtools_host, devtools_host,
+ ContentSettingsType::FILE_SYSTEM_WRITE_GUARD));
+ EXPECT_EQ(CONTENT_SETTING_BLOCK,
+ host_content_settings_map->GetContentSetting(
+ example_host, example_host,
+ ContentSettingsType::FILE_SYSTEM_WRITE_GUARD));
+}
+#endif // !BUILDFLAG(IS_ANDROID)
diff --git a/components/content_settings/core/browser/content_settings_registry.cc b/components/content_settings/core/browser/content_settings_registry.cc
index 8021bd809315debd7171350187bbd684c23fd882..69c66a5e68f6a137875df19993a959000c56a2e6 100644
--- a/components/content_settings/core/browser/content_settings_registry.cc
+++ b/components/content_settings/core/browser/content_settings_registry.cc
@@ -425,7 +425,8 @@ void ContentSettingsRegistry::Init() {
Register(ContentSettingsType::FILE_SYSTEM_WRITE_GUARD,
"file-system-write-guard", CONTENT_SETTING_ASK,
- WebsiteSettingsInfo::UNSYNCABLE, /*allowlisted_schemes=*/{},
+ WebsiteSettingsInfo::UNSYNCABLE,
+ /*allowlisted_primary_schemes=*/{kChromeDevToolsScheme},
/*valid_settings=*/
{CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK, CONTENT_SETTING_BLOCK},
WebsiteSettingsInfo::TOP_ORIGIN_ONLY_SCOPE,

View File

@@ -0,0 +1,36 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Peng Huang <penghuang@chromium.org>
Date: Wed, 20 Mar 2024 16:22:16 +0000
Subject: Fix PaintImage deserialization arbitrary-read issue
(cherry picked from commit 47e8386c97ac7a84a96866fbd35422b99a01de5a)
Bug: 327183408
Change-Id: I09927fbae60b666aaa370e3aba01607cdb977a25
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5370455
Reviewed-by: Sunny Sachanandani <sunnyps@chromium.org>
Commit-Queue: Peng Huang <penghuang@chromium.org>
Cr-Original-Commit-Position: refs/heads/main@{#1272930}
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5382202
Auto-Submit: Peng Huang <penghuang@chromium.org>
Commit-Queue: Sunny Sachanandani <sunnyps@chromium.org>
Cr-Commit-Position: refs/branch-heads/6261@{#1106}
Cr-Branched-From: 9755d9d81e4a8cb5b4f76b23b761457479dbb06b-refs/heads/main@{#1250580}
diff --git a/cc/paint/paint_op_reader.cc b/cc/paint/paint_op_reader.cc
index 128d4306319d039f0a1dc3ab48793dbdcc641da0..936251f2c45c18464bb557bfc9ac600ba5b9510b 100644
--- a/cc/paint/paint_op_reader.cc
+++ b/cc/paint/paint_op_reader.cc
@@ -1568,9 +1568,10 @@ inline void PaintOpReader::DidRead(size_t bytes_read) {
// All data are aligned with PaintOpWriter::kDefaultAlignment at least.
size_t aligned_bytes =
base::bits::AlignUp(bytes_read, PaintOpWriter::kDefaultAlignment);
- memory_ += aligned_bytes;
DCHECK_LE(aligned_bytes, remaining_bytes_);
- remaining_bytes_ -= aligned_bytes;
+ bytes_read = std::min(aligned_bytes, remaining_bytes_);
+ memory_ += bytes_read;
+ remaining_bytes_ -= bytes_read;
}
} // namespace cc

View File

@@ -0,0 +1,41 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Joey Arhar <jarhar@chromium.org>
Date: Wed, 21 Feb 2024 21:06:46 +0000
Subject: M122: cherry pick CVE-2024-25062 libxml fix
This patch cherry picks the CVE-2024-25062 fix from libxml:
https://gitlab.gnome.org/GNOME/libxml2/-/commit/1a66b176055d25ee635bf328c7b35b381db0b71d
Bug: 325094430
Change-Id: I526ee718269ed8700b90885630b67f00f2f95089
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5310037
Auto-Submit: Joey Arhar <jarhar@chromium.org>
Commit-Queue: David Baron <dbaron@chromium.org>
Reviewed-by: David Baron <dbaron@chromium.org>
Commit-Queue: Joey Arhar <jarhar@chromium.org>
Cr-Commit-Position: refs/branch-heads/6261@{#913}
Cr-Branched-From: 9755d9d81e4a8cb5b4f76b23b761457479dbb06b-refs/heads/main@{#1250580}
diff --git a/third_party/libxml/README.chromium b/third_party/libxml/README.chromium
index 33cfec99e14c5090f6f9ac504689f2c2b482806c..a9a90fccb30f049e544923b5e4e28c67e63794f5 100644
--- a/third_party/libxml/README.chromium
+++ b/third_party/libxml/README.chromium
@@ -36,5 +36,6 @@ Modifications:
- LIBXML_XINCLUDE_ENABLED
- LIBXML_XPTR_ENABLED
- LIBXML_ZLIB_ENABLED
+- Cherry picked fix for CVE-2024-25062
This import was generated by the chromium/roll.py script.
diff --git a/third_party/libxml/src/xmlreader.c b/third_party/libxml/src/xmlreader.c
index c04cb11311c2af03608f62b54f8d6ae58a6c1d93..9ce8a148b6806f39e5ce14e114bac1af767f5a50 100644
--- a/third_party/libxml/src/xmlreader.c
+++ b/third_party/libxml/src/xmlreader.c
@@ -1378,6 +1378,7 @@ node_found:
* Handle XInclude if asked for
*/
if ((reader->xinclude) && (reader->in_xinclude == 0) &&
+ (reader->state != XML_TEXTREADER_BACKTRACK) &&
(reader->node != NULL) &&
(reader->node->type == XML_ELEMENT_NODE) &&
(reader->node->ns != NULL) &&

View File

@@ -0,0 +1,80 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Eugene Zemtsov <eugene@chromium.org>
Date: Mon, 25 Mar 2024 19:28:44 +0000
Subject: webcodecs: Disable async VideoFrame readback to mitigate a race
(cherry picked from commit fdc363eb7a1c1c194a02a4cb340534b1501b0f95)
Bug: 330575496
Change-Id: I187a113528da9d1c4316186e3dd24f91dbfd818b
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5386784
Commit-Queue: Eugene Zemtsov <eugene@chromium.org>
Reviewed-by: Dale Curtis <dalecurtis@chromium.org>
Cr-Original-Commit-Position: refs/heads/main@{#1277172}
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5391828
Reviewed-by: Eugene Zemtsov <eugene@chromium.org>
Commit-Queue: Dale Curtis <dalecurtis@chromium.org>
Reviewed-by: Xiaohan Wang <xhwang@chromium.org>
Commit-Queue: Xiaohan Wang <xhwang@chromium.org>
Auto-Submit: Dale Curtis <dalecurtis@chromium.org>
Cr-Commit-Position: refs/branch-heads/6261@{#1124}
Cr-Branched-From: 9755d9d81e4a8cb5b4f76b23b761457479dbb06b-refs/heads/main@{#1250580}
diff --git a/content/test/data/gpu/webcodecs/copyTo.html b/content/test/data/gpu/webcodecs/copyTo.html
index ec2455c9c18900ad911ce98f326139cbdeabd84f..9453c8d361a572b500e86b1249896bc4114ebe27 100644
--- a/content/test/data/gpu/webcodecs/copyTo.html
+++ b/content/test/data/gpu/webcodecs/copyTo.html
@@ -118,6 +118,16 @@ Take frames coming from various sources and read them using copyTo().
let frame = await source.getNextFrame();
let size = frame.allocationSize();
+ // Readback a whole frame to a regular buffer detach it
+ {
+ let buf = new ArrayBuffer(size);
+ TEST.assert(readWholeBuffer(buf) == 0, "Buffer should be zero");
+ let copy_promise = frame.copyTo(buf);
+ buf.transfer(1);
+ let layout = await copy_promise;
+ TEST.assert(layout, "layout is empty / ArrayBuffer");
+ }
+
// Readback a whole frame to a regular buffer and send it to a worker
{
let {worker, worker_promise } = makeWorker();
@@ -158,4 +168,5 @@ Take frames coming from various sources and read them using copyTo().
TEST.log('Test completed');
}
addManualTestButton([{'source_type': 'offscreen'}]);
+ addManualTestButton([{'source_type': 'arraybuffer'}]);
</script>
diff --git a/third_party/blink/renderer/modules/webcodecs/video_frame.cc b/third_party/blink/renderer/modules/webcodecs/video_frame.cc
index e5860706c0d9098980ee1e901f1eac048be1a011..af4b7082bebb96b8e6d766c950cf34d5747d10d3 100644
--- a/third_party/blink/renderer/modules/webcodecs/video_frame.cc
+++ b/third_party/blink/renderer/modules/webcodecs/video_frame.cc
@@ -80,6 +80,11 @@ namespace blink {
namespace {
+// Controls if VideoFrame.copyTo() reads GPU frames asynchronously
+BASE_FEATURE(kVideoFrameAsyncCopyTo,
+ "VideoFrameAsyncCopyTo",
+ base::FEATURE_DISABLED_BY_DEFAULT);
+
media::VideoPixelFormat ToMediaPixelFormat(V8VideoPixelFormat::Enum fmt) {
switch (fmt) {
case V8VideoPixelFormat::Enum::kI420:
@@ -1157,9 +1162,11 @@ ScriptPromise VideoFrame::copyTo(ScriptState* script_state,
} else {
DCHECK(local_frame->HasTextures());
- if (auto* resolver = CopyToAsync(script_state, local_frame, src_rect,
- destination, dest_layout)) {
- return resolver->Promise();
+ if (base::FeatureList::IsEnabled(kVideoFrameAsyncCopyTo)) {
+ if (auto* resolver = CopyToAsync(script_state, local_frame, src_rect,
+ destination, dest_layout)) {
+ return resolver->Promise();
+ }
}
if (!CopyTexturablePlanes(*local_frame, src_rect, dest_layout, buffer)) {

View File

@@ -0,0 +1,156 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Ken Rockot <rockot@google.com>
Date: Thu, 15 Feb 2024 20:30:22 +0000
Subject: Prevent MojoTrap event re-ordering
(cherry picked from commit 3557a2fcbdd8167f97ca81171be2e0da9c4f0647)
Fixed: 1508753
Change-Id: I9ec14a12e7d1d147bda63703e1d6619fa30c8a51
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5253039
Commit-Queue: Ken Rockot <rockot@google.com>
Reviewed-by: Robert Sesek <rsesek@chromium.org>
Cr-Original-Commit-Position: refs/heads/main@{#1254840}
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5299857
Reviewed-by: Oksana Zhuravlova <oksamyt@chromium.org>
Commit-Queue: Alex Gough <ajgo@chromium.org>
Cr-Commit-Position: refs/branch-heads/6261@{#794}
Cr-Branched-From: 9755d9d81e4a8cb5b4f76b23b761457479dbb06b-refs/heads/main@{#1250580}
diff --git a/mojo/core/ipcz_driver/mojo_trap.cc b/mojo/core/ipcz_driver/mojo_trap.cc
index 7a5765a74a7f64e584b0a080e659c88c019adcbb..2c98335dd7846fe44fd048265078dfffcb0b63f6 100644
--- a/mojo/core/ipcz_driver/mojo_trap.cc
+++ b/mojo/core/ipcz_driver/mojo_trap.cc
@@ -544,7 +544,15 @@ void MojoTrap::DispatchOrQueueEvent(Trigger& trigger,
}
dispatching_thread_ = base::PlatformThread::CurrentRef();
- DispatchEvent(event);
+
+ // If `trigger.removed` is true, then either this is the cancellation event
+ // for the trigger (in which case it's OK to dispatch), or it was cancelled on
+ // some other thread while we were blocked above. In the latter case, this
+ // event is no longer valid and cannot be dispatched.
+ // See https://crbug.com/1508753.
+ if (!trigger.removed || event.result == MOJO_RESULT_CANCELLED) {
+ DispatchEvent(event);
+ }
// NOTE: This vector is only shrunk by the clear() below, but it may
// accumulate more events during each iteration. Hence we iterate by index.
diff --git a/mojo/core/trap_unittest.cc b/mojo/core/trap_unittest.cc
index 0fd449d9598810fd34372d69d1d1599a0c88b955..4058da72eef8b5a11432b9a17d6ff3ecfd1306e8 100644
--- a/mojo/core/trap_unittest.cc
+++ b/mojo/core/trap_unittest.cc
@@ -1747,6 +1747,111 @@ TEST_F(TrapTest, TriggerDuringDestruction) {
MojoClose(b);
}
+TEST_F(TrapTest, RaceDispatchAndBlockedCancel) {
+ // Regression test for https://crbug.com/1508753. This bug was caused by
+ // reordering of a MOJO_RESULT_CANCELLED event to before some other event for
+ // the same trap context, violating an API constraint that must be upheld for
+ // memory safety in application code. The scenario which could elicit the bug
+ // was as follows:
+ //
+ // 1. A single trap is watching two pipes, P and Q.
+ // 2. Thread A closes pipe P, triggering a CANCELLED event.
+ // 3. Thread A re-arms the trap from within the CANCELLED event handler.
+ // 4. Thread B changes Q's state to elicit a event for Q (not CANCELLED).
+ // 5. Thread B dispatch is blocked because thread A is still dispatching.
+ // 6. Before thread B gets a chance to be scheduled, thread A closes Q.
+ // 7. Thread A dispatches a CANCELLED event for Q.
+ // 8. Thread B is scheduled and proceeds to dispatch its Q event. [BAD]
+
+ struct State;
+
+ struct Pipe {
+ explicit Pipe(State* state) : state(state) { CreateMessagePipe(&a, &b); }
+
+ uintptr_t context() const { return reinterpret_cast<uintptr_t>(this); }
+
+ MojoHandle a;
+ MojoHandle b;
+ bool trigger_cancelled = false;
+
+ // Back-reference to common state so it's reachable from the event handler.
+ const raw_ptr<State> state;
+ };
+
+ struct State {
+ Pipe pipe0{this};
+ Pipe pipe1{this};
+ MojoHandle trap;
+ base::WaitableEvent event;
+ };
+ State state;
+
+ // NOTE: + to turn the lambda into a function pointer.
+ const MojoTrapEventHandler event_handler = +[](const MojoTrapEvent* event) {
+ auto& pipe = *reinterpret_cast<Pipe*>(event->trigger_context);
+ auto& state = *pipe.state;
+
+ // If the bug is present, this expectation can fail flakily. No event should
+ // fire for a pipe after its watch has been cancelled.
+ EXPECT_FALSE(pipe.trigger_cancelled);
+
+ if (event->result == MOJO_RESULT_CANCELLED) {
+ pipe.trigger_cancelled = true;
+
+ if (&pipe == &state.pipe0) {
+ // When pipe0's watch is cancelled (on the main thread by closure down
+ // below) we re-arm the trap immediately. This must succeed because
+ // `pipe1.a` is now the only handle being watched, and it's still in an
+ // uninteresting state.
+ EXPECT_EQ(MOJO_RESULT_OK,
+ MojoArmTrap(state.trap, nullptr, nullptr, nullptr));
+
+ // Unblock the other thread so it can elicit a trap event on pipe1 now
+ // that the trap is re-armed. It will still block just before
+ // dispatching as long as we're still in this event handler on the main
+ // thread.
+ state.event.Signal();
+
+ // A nice long delay to make it very likely for the waiting
+ // ThreadedRunner to progress right up to its event dispatch.
+ base::PlatformThread::Sleep(base::Milliseconds(10));
+
+ // Trigger cancellation for pipe1 by closing its `a`. This will queue a
+ // CANCELLED event to fire on the same thread immediately after we
+ // return from this handler.
+ MojoClose(state.pipe1.a);
+ }
+ }
+ };
+
+ EXPECT_EQ(MOJO_RESULT_OK,
+ MojoCreateTrap(event_handler, nullptr, &state.trap));
+ EXPECT_EQ(
+ MOJO_RESULT_OK,
+ MojoAddTrigger(state.trap, state.pipe0.a, MOJO_HANDLE_SIGNAL_READABLE,
+ MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
+ state.pipe0.context(), nullptr));
+ EXPECT_EQ(
+ MOJO_RESULT_OK,
+ MojoAddTrigger(state.trap, state.pipe1.a, MOJO_HANDLE_SIGNAL_READABLE,
+ MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
+ state.pipe1.context(), nullptr));
+ EXPECT_EQ(MOJO_RESULT_OK, MojoArmTrap(state.trap, nullptr, nullptr, nullptr));
+
+ ThreadedRunner close_pipe1_b(base::BindLambdaForTesting([&] {
+ state.event.Wait();
+ MojoClose(state.pipe1.b);
+ }));
+ close_pipe1_b.Start();
+
+ // Trigger cancellation of the watch on `pipe0.a`. See event_handler above.
+ MojoClose(state.pipe0.a);
+
+ close_pipe1_b.Join();
+ MojoClose(state.pipe0.b);
+ MojoClose(state.trap);
+}
+
base::RepeatingClosure g_do_random_thing_callback;
void ReadAllMessages(const MojoTrapEvent* event) {

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,74 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Joshua Peraza <jperaza@chromium.org>
Date: Tue, 5 Mar 2024 18:09:48 +0000
Subject: Update Crashpad to 37afd37401253ebcebcf6e07ce15c8cfecb1a1cc
29ac83caeb94 [Fuchsia] remove use of fuchsia mac sdk
37afd3740125 Properly update iterator
(cherry picked from commit 80b0e498bec1722e8cc310fe52698e7b690956f2)
Bug: 325296797
Change-Id: I7eb39d1bccec802f1b043eebd20ec0e658fe0e04
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5311633
Reviewed-by: Nico Weber <thakis@chromium.org>
Cr-Original-Commit-Position: refs/heads/main@{#1264232}
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5335538
Reviewed-by: Mark Mentovai <mark@chromium.org>
Commit-Queue: Joshua Peraza <jperaza@chromium.org>
Cr-Commit-Position: refs/branch-heads/6261@{#1024}
Cr-Branched-From: 9755d9d81e4a8cb5b4f76b23b761457479dbb06b-refs/heads/main@{#1250580}
diff --git a/third_party/crashpad/README.chromium b/third_party/crashpad/README.chromium
index e6eb8320371f0f367c131d1712cc0f4d1f410b77..3c3c141e10522d782cd13b5aaa32a640897323e7 100644
--- a/third_party/crashpad/README.chromium
+++ b/third_party/crashpad/README.chromium
@@ -2,7 +2,7 @@ Name: Crashpad
Short Name: crashpad
URL: https://crashpad.chromium.org/
Version: N/A
-Revision: 4a93d7f4c407fee2168ea23195d0e30fbfc1f90c
+Revision: 37afd37401253ebcebcf6e07ce15c8cfecb1a1cc
License: Apache 2.0
License File: crashpad/LICENSE
Security Critical: yes
diff --git a/third_party/crashpad/crashpad/DEPS b/third_party/crashpad/crashpad/DEPS
index 909ef7dce53d53486a21cd87e00dc63d3eb79b43..cea46fda079b0bd2aca4bfaeb53158d672cb2b31 100644
--- a/third_party/crashpad/crashpad/DEPS
+++ b/third_party/crashpad/crashpad/DEPS
@@ -121,16 +121,6 @@ deps = {
'0d6902558d92fe3d49ba9a8f638ddea829be595b',
'condition': 'checkout_fuchsia',
},
- 'crashpad/third_party/fuchsia/sdk/mac-amd64': {
- 'packages': [
- {
- 'package': 'fuchsia/sdk/core/mac-amd64',
- 'version': 'latest'
- },
- ],
- 'condition': 'checkout_fuchsia and host_os == "mac"',
- 'dep_type': 'cipd'
- },
'crashpad/third_party/fuchsia/sdk/linux-amd64': {
'packages': [
{
diff --git a/third_party/crashpad/crashpad/snapshot/sanitized/module_snapshot_sanitized.cc b/third_party/crashpad/crashpad/snapshot/sanitized/module_snapshot_sanitized.cc
index 0ad2ee97540174be07110f08e519b530aae045f5..c76722683ddf1ae1a562b3705d909a337a23621b 100644
--- a/third_party/crashpad/crashpad/snapshot/sanitized/module_snapshot_sanitized.cc
+++ b/third_party/crashpad/crashpad/snapshot/sanitized/module_snapshot_sanitized.cc
@@ -99,9 +99,11 @@ ModuleSnapshotSanitized::AnnotationsSimpleMap() const {
std::map<std::string, std::string> annotations =
snapshot_->AnnotationsSimpleMap();
if (allowed_annotations_) {
- for (auto kv = annotations.begin(); kv != annotations.end(); ++kv) {
- if (!KeyIsAllowed(kv->first, *allowed_annotations_)) {
- annotations.erase(kv);
+ for (auto kv = annotations.begin(); kv != annotations.end();) {
+ if (KeyIsAllowed(kv->first, *allowed_annotations_)) {
+ ++kv;
+ } else {
+ kv = annotations.erase(kv);
}
}
}

View File

@@ -1,25 +1,17 @@
{
"src/electron/patches/chromium": "src",
"src/electron/patches/boringssl": "src/third_party/boringssl/src",
"src/electron/patches/devtools_frontend": "src/third_party/devtools-frontend/src",
"src/electron/patches/ffmpeg": "src/third_party/ffmpeg",
"src/electron/patches/v8": "src/v8",
"src/electron/patches/node": "src/third_party/electron_node",
"src/electron/patches/nan": "src/third_party/nan",
"src/electron/patches/perfetto": "src/third_party/perfetto",
"src/electron/patches/squirrel.mac": "src/third_party/squirrel.mac",
"src/electron/patches/Mantle": "src/third_party/squirrel.mac/vendor/Mantle",
"src/electron/patches/ReactiveObjC": "src/third_party/squirrel.mac/vendor/ReactiveObjC",
"src/electron/patches/webrtc": "src/third_party/webrtc"
}
[
{ "patch_dir": "src/electron/patches/chromium", "repo": "src" },
{ "patch_dir": "src/electron/patches/boringssl", "repo": "src/third_party/boringssl/src" },
{ "patch_dir": "src/electron/patches/devtools_frontend", "repo": "src/third_party/devtools-frontend/src" },
{ "patch_dir": "src/electron/patches/ffmpeg", "repo": "src/third_party/ffmpeg" },
{ "patch_dir": "src/electron/patches/v8", "repo": "src/v8" },
{ "patch_dir": "src/electron/patches/node", "repo": "src/third_party/electron_node" },
{ "patch_dir": "src/electron/patches/nan", "repo": "src/third_party/nan" },
{ "patch_dir": "src/electron/patches/perfetto", "repo": "src/third_party/perfetto" },
{ "patch_dir": "src/electron/patches/squirrel.mac", "repo": "src/third_party/squirrel.mac" },
{ "patch_dir": "src/electron/patches/Mantle", "repo": "src/third_party/squirrel.mac/vendor/Mantle" },
{ "patch_dir": "src/electron/patches/ReactiveObjC", "repo": "src/third_party/squirrel.mac/vendor/ReactiveObjC" },
{ "patch_dir": "src/electron/patches/webrtc", "repo": "src/third_party/webrtc" },
{ "patch_dir": "src/electron/patches/angle", "repo": "src/third_party/angle" },
{ "patch_dir": "src/electron/patches/libvpx", "repo": "src/third_party/libvpx/source/libvpx" },
{ "patch_dir": "src/electron/patches/dxc", "repo": "src/third_party/dawn/third_party/dxc" }
]

1
patches/dxc/.patches Normal file
View File

@@ -0,0 +1 @@
fix_hlmatrixlowerpass_leaving_call_to_dangling_functionval.patch

View File

@@ -0,0 +1,36 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Antonio Maiorano <amaiorano@google.com>
Date: Wed, 20 Mar 2024 17:15:40 -0400
Subject: Fix HLMatrixLowerPass leaving call to dangling FunctionVal
When lowering an hl.cast, when the operand was an undef matrix, the pass would insert a call to a mat2vec stub, but since the undef value is not
an alloca, it never gets handled, and the call to the temporary stub
remains. Since the stub FunctionVal gets deleted, when the instruction
is accessed in a future pass, it reads a dangling pointer.
The fix is to handle undef similarly to how constant 0 is handled, and
to return an undef vector from lowerHLCast.
Bug: chromium:328958020
Change-Id: Id31e3aa326d9cb9f03ea97139f14dc5292cd6f7b
Reviewed-on: https://chromium-review.googlesource.com/c/external/github.com/microsoft/DirectXShaderCompiler/+/5383595
Reviewed-by: Ben Clayton <bclayton@chromium.org>
Reviewed-by: David Neto <dneto@google.com>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
diff --git a/lib/HLSL/HLMatrixLowerPass.cpp b/lib/HLSL/HLMatrixLowerPass.cpp
index ca8a8a33fdb475542b3705f3f7a8b8af2554a21f..d5959eb9335465f67d8e7ef7d7ab4eb720274226 100644
--- a/lib/HLSL/HLMatrixLowerPass.cpp
+++ b/lib/HLSL/HLMatrixLowerPass.cpp
@@ -421,6 +421,11 @@ Value *HLMatrixLowerPass::getLoweredByValOperand(Value *Val,
if (isa<ConstantAggregateZero>(Val))
return ConstantAggregateZero::get(LoweredTy);
+ // Lower undef mat as undef vec
+ if (isa<UndefValue>(Val)) {
+ return UndefValue::get(LoweredTy);
+ }
+
// Return a mat-to-vec translation stub
FunctionType *TranslationStubTy =
FunctionType::get(LoweredTy, {Ty}, /* isVarArg */ false);

2
patches/libvpx/.patches Normal file
View File

@@ -0,0 +1,2 @@
fix_to_buffer_alloc_for_vp9_bitstream_worker_data.patch
vp9_fix_to_integer_overflow_test.patch

View File

@@ -0,0 +1,68 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Marco Paniconi <marpan@google.com>
Date: Wed, 13 Mar 2024 10:58:17 -0700
Subject: Fix to buffer alloc for vp9_bitstream_worker_data
The code was using the bitstream_worker_data when it
wasn't allocated for big enough size. This is because
the existing condition was to only re-alloc the
bitstream_worker_data when current dest_size was larger
than the current frame_size. But under resolution change
where frame_size is increased, beyond the current dest_size,
we need to allow re-alloc to the new size.
The existing condition to re-alloc when dest_size is
larger than frame_size (which is not required) is kept
for now.
Also increase the dest_size to account for image format.
Added tests, for both ROW_MT=0 and 1, that reproduce
the failures in the bugs below.
Note: this issue only affects the REALTIME encoding path.
Bug: b/329088759, b/329674887, b/329179808
Change-Id: Icd65dbc5317120304d803f648d4bd9405710db6f
(cherry picked from commit c29e63728316486082dd6083c2062434b441b77d)
diff --git a/vp9/encoder/vp9_bitstream.c b/vp9/encoder/vp9_bitstream.c
index ca56d14aa1e31e4791f8772316e449b771aae4fc..88a031e5fc1cf7b6cf0a441664dbbc62006c1790 100644
--- a/vp9/encoder/vp9_bitstream.c
+++ b/vp9/encoder/vp9_bitstream.c
@@ -962,6 +962,14 @@ void vp9_bitstream_encode_tiles_buffer_dealloc(VP9_COMP *const cpi) {
}
}
+static int encode_tiles_buffer_alloc_size(VP9_COMP *const cpi) {
+ VP9_COMMON *const cm = &cpi->common;
+ const int image_bps =
+ (8 + 2 * (8 >> (cm->subsampling_x + cm->subsampling_y))) *
+ (1 + (cm->bit_depth > 8));
+ return cpi->oxcf.width * cpi->oxcf.height * image_bps / 8;
+}
+
static void encode_tiles_buffer_alloc(VP9_COMP *const cpi) {
VP9_COMMON *const cm = &cpi->common;
int i;
@@ -972,7 +980,7 @@ static void encode_tiles_buffer_alloc(VP9_COMP *const cpi) {
memset(cpi->vp9_bitstream_worker_data, 0, worker_data_size);
for (i = 1; i < cpi->num_workers; ++i) {
cpi->vp9_bitstream_worker_data[i].dest_size =
- cpi->oxcf.width * cpi->oxcf.height;
+ encode_tiles_buffer_alloc_size(cpi);
CHECK_MEM_ERROR(&cm->error, cpi->vp9_bitstream_worker_data[i].dest,
vpx_malloc(cpi->vp9_bitstream_worker_data[i].dest_size));
}
@@ -987,8 +995,8 @@ static size_t encode_tiles_mt(VP9_COMP *cpi, uint8_t *data_ptr) {
int tile_col = 0;
if (!cpi->vp9_bitstream_worker_data ||
- cpi->vp9_bitstream_worker_data[1].dest_size >
- (cpi->oxcf.width * cpi->oxcf.height)) {
+ cpi->vp9_bitstream_worker_data[1].dest_size !=
+ encode_tiles_buffer_alloc_size(cpi)) {
vp9_bitstream_encode_tiles_buffer_dealloc(cpi);
encode_tiles_buffer_alloc(cpi);
}

View File

@@ -0,0 +1,28 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Marco Paniconi <marpan@google.com>
Date: Sat, 16 Mar 2024 10:39:28 -0700
Subject: vp9: fix to integer overflow test
failure for the 16k test: issue introduced
in: c29e637283
Bug: b/329088759, b/329674887, b/329179808
Change-Id: I88e8a36b7f13223997c3006c84aec9cfa48c0bcf
(cherry picked from commit 19832b1702d5b0adf616a0e080abd5207c8445b5)
diff --git a/vp9/encoder/vp9_bitstream.c b/vp9/encoder/vp9_bitstream.c
index 88a031e5fc1cf7b6cf0a441664dbbc62006c1790..d3c029da4bacafdb19aa6bfb9865ccbf2db33393 100644
--- a/vp9/encoder/vp9_bitstream.c
+++ b/vp9/encoder/vp9_bitstream.c
@@ -967,7 +967,9 @@ static int encode_tiles_buffer_alloc_size(VP9_COMP *const cpi) {
const int image_bps =
(8 + 2 * (8 >> (cm->subsampling_x + cm->subsampling_y))) *
(1 + (cm->bit_depth > 8));
- return cpi->oxcf.width * cpi->oxcf.height * image_bps / 8;
+ const int64_t size =
+ (int64_t)cpi->oxcf.width * cpi->oxcf.height * image_bps / 8;
+ return (int)size;
}
static void encode_tiles_buffer_alloc(VP9_COMP *const cpi) {

View File

@@ -53,5 +53,6 @@ win_process_avoid_assert_after_spawning_store_app_4152.patch
test_fix_edge_snapshot_stack_traces.patch
chore_remove_use_of_deprecated_kmaxlength.patch
fix_avx_detection.patch
src_preload_function_for_environment.patch
fix_undici_incorrectly_copies_headers_onto_fetches.patch
module_rework_of_memory_management_in_vm_apis_with_the.patch
src_preload_function_for_environment.patch

File diff suppressed because it is too large Load Diff

View File

@@ -1,29 +1,15 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Cheng Zhao <zcbenz@gmail.com>
Date: Mon, 22 Jan 2024 13:45:55 +0900
Date: Mon, 4 Mar 2024 11:41:18 +0900
Subject: src: preload function for Environment
https://github.com/nodejs/node/pull/51539
This PR adds a |preload| arg to the node::CreateEnvironment to allow
embedders to set a preload function for the environment, which will run
after the environment is loaded and before the main script runs.
This is similiar to the --require CLI option, but runs a C++ function,
and can only be set by embedders.
The preload function can be used by embedders to inject scripts before
running the main script, for example:
1. In Electron it is used to initialize the ASAR virtual filesystem,
inject custom process properties, etc.
2. In VS Code it can be used to reset the module search paths for
extensions.
Backport https://github.com/nodejs/node/pull/51539
diff --git a/lib/internal/process/pre_execution.js b/lib/internal/process/pre_execution.js
index fd5357997a4e05567146dc997e47af408e1fc8f4..cb53212069794eaac8ceaf28001f5db25e127f0a 100644
index 2d892267a08772f4c37ee381c55f46b3a99f2232..e3daca3ba8cddac8db5fc73d78d869fedb4204af 100644
--- a/lib/internal/process/pre_execution.js
+++ b/lib/internal/process/pre_execution.js
@@ -127,6 +127,9 @@ function setupUserModules() {
@@ -126,6 +126,9 @@ function setupUserModules() {
initializeESMLoader();
const CJSLoader = require('internal/modules/cjs/loader');
assert(!CJSLoader.hasLoadedAnyUserCJSModule);
@@ -33,7 +19,7 @@ index fd5357997a4e05567146dc997e47af408e1fc8f4..cb53212069794eaac8ceaf28001f5db2
loadPreloadModules();
// Need to be done after --require setup.
initializeFrozenIntrinsics();
@@ -601,6 +604,10 @@ function initializeFrozenIntrinsics() {
@@ -588,6 +591,10 @@ function initializeFrozenIntrinsics() {
}
}
@@ -45,120 +31,80 @@ index fd5357997a4e05567146dc997e47af408e1fc8f4..cb53212069794eaac8ceaf28001f5db2
// For user code, we preload modules if `-r` is passed
const preloadModules = getOptionValue('--require');
diff --git a/src/api/environment.cc b/src/api/environment.cc
index c4caef25af670658965fc740ce03c2d2c4ed3e66..19443a9672441da5b98921eab9385083a72e3b7e 100644
index c4caef25af670658965fc740ce03c2d2c4ed3e66..465ff36b79c36d29777c7b1abe3a35d3be5de93e 100644
--- a/src/api/environment.cc
+++ b/src/api/environment.cc
@@ -404,14 +404,16 @@ Environment* CreateEnvironment(
const std::vector<std::string>& exec_args,
EnvironmentFlags::Flags flags,
ThreadId thread_id,
- std::unique_ptr<InspectorParentHandle> inspector_parent_handle) {
+ std::unique_ptr<InspectorParentHandle> inspector_parent_handle,
+ EmbedderPreloadCallback preload) {
Isolate* isolate = context->GetIsolate();
HandleScope handle_scope(isolate);
Context::Scope context_scope(context);
// TODO(addaleax): This is a much better place for parsing per-Environment
// options than the global parse call.
Environment* env = new Environment(
- isolate_data, context, args, exec_args, nullptr, flags, thread_id);
+ isolate_data, context, args, exec_args, nullptr, flags, thread_id,
+ std::move(preload));
@@ -484,18 +484,22 @@ NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
#endif
}
#if HAVE_INSPECTOR
if (env->should_create_inspector()) {
-MaybeLocal<Value> LoadEnvironment(
- Environment* env,
- StartExecutionCallback cb) {
+MaybeLocal<Value> LoadEnvironment(Environment* env,
+ StartExecutionCallback cb,
+ EmbedderPreloadCallback preload) {
env->InitializeLibuv();
env->InitializeDiagnostics();
+ if (preload) {
+ env->set_embedder_preload(std::move(preload));
+ }
return StartExecution(env, cb);
}
MaybeLocal<Value> LoadEnvironment(
Environment* env,
- const char* main_script_source_utf8) {
+ const char* main_script_source_utf8,
+ EmbedderPreloadCallback preload) {
CHECK_NOT_NULL(main_script_source_utf8);
return LoadEnvironment(
env, [&](const StartExecutionCallbackInfo& info) -> MaybeLocal<Value> {
@@ -508,7 +512,8 @@ MaybeLocal<Value> LoadEnvironment(
std::vector<Local<Value>> args = {realm->process_object(),
realm->builtin_module_require()};
return realm->ExecuteBootstrapper(name.c_str(), &args);
- });
+ },
+ std::move(preload));
}
Environment* GetCurrentEnvironment(Local<Context> context) {
diff --git a/src/env-inl.h b/src/env-inl.h
index 103dc6711e71e15da640edc5e017bc638ddc6ad1..4d12e6e406c1078fd92f3cc837c2f8a926fadd1d 100644
index c68ea0fb1d45fadfa64f092a96ee04ecd9fe4c2d..2db4d431b3ce573e77e282b74c06a57a38d09417 100644
--- a/src/env-inl.h
+++ b/src/env-inl.h
@@ -388,6 +388,10 @@ inline std::vector<double>* Environment::destroy_async_id_list() {
@@ -378,6 +378,14 @@ inline std::vector<double>* Environment::destroy_async_id_list() {
return &destroy_async_id_list_;
}
+inline const EmbedderPreloadCallback& Environment::embedder_preload() const {
+ return embedder_preload_;
+}
+
+inline void Environment::set_embedder_preload(EmbedderPreloadCallback fn) {
+ embedder_preload_ = std::move(fn);
+}
+
inline double Environment::new_async_id() {
async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
diff --git a/src/env.cc b/src/env.cc
index 5bdbfad4f4d3ef16c41ff8e5dae90f48a6d5f5a2..98fd9bdcf99e7ddcd4ae6baa23998b855cc3ddfe 100644
--- a/src/env.cc
+++ b/src/env.cc
@@ -643,7 +643,8 @@ Environment::Environment(IsolateData* isolate_data,
const std::vector<std::string>& exec_args,
const EnvSerializeInfo* env_info,
EnvironmentFlags::Flags flags,
- ThreadId thread_id)
+ ThreadId thread_id,
+ EmbedderPreloadCallback preload)
: isolate_(isolate),
isolate_data_(isolate_data),
async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
@@ -666,7 +667,8 @@ Environment::Environment(IsolateData* isolate_data,
flags_(flags),
thread_id_(thread_id.id == static_cast<uint64_t>(-1)
? AllocateEnvironmentThreadId().id
- : thread_id.id) {
+ : thread_id.id),
+ embedder_preload_(std::move(preload)) {
// We'll be creating new objects so make sure we've entered the context.
HandleScope handle_scope(isolate);
@@ -736,14 +738,16 @@ Environment::Environment(IsolateData* isolate_data,
const std::vector<std::string>& exec_args,
const EnvSerializeInfo* env_info,
EnvironmentFlags::Flags flags,
- ThreadId thread_id)
+ ThreadId thread_id,
+ EmbedderPreloadCallback preload)
: Environment(isolate_data,
context->GetIsolate(),
args,
exec_args,
env_info,
flags,
- thread_id) {
+ thread_id,
+ std::move(preload)) {
InitializeMainContext(context, env_info);
}
diff --git a/src/env.h b/src/env.h
index 36e8e7d960a95a9040ad963c79a7f66c89233c87..1b11c4243d18f14f4aaaad2683295ffff49dfd04 100644
index 9b5fcdaed5fdda44cd8103a0821a7b5358523f4e..6a5a7eeec866f6e501feeb03fe7da5ada011afa0 100644
--- a/src/env.h
+++ b/src/env.h
@@ -579,7 +579,8 @@ class Environment : public MemoryRetainer {
const std::vector<std::string>& exec_args,
const EnvSerializeInfo* env_info,
EnvironmentFlags::Flags flags,
- ThreadId thread_id);
+ ThreadId thread_id,
+ EmbedderPreloadCallback preload);
void InitializeMainContext(v8::Local<v8::Context> context,
const EnvSerializeInfo* env_info);
// Create an Environment and initialize the provided principal context for it.
@@ -589,7 +590,8 @@ class Environment : public MemoryRetainer {
const std::vector<std::string>& exec_args,
const EnvSerializeInfo* env_info,
EnvironmentFlags::Flags flags,
- ThreadId thread_id);
+ ThreadId thread_id,
+ EmbedderPreloadCallback preload);
~Environment() override;
void InitializeLibuv();
@@ -933,6 +935,8 @@ class Environment : public MemoryRetainer {
@@ -925,6 +925,9 @@ class Environment : public MemoryRetainer {
#endif // HAVE_INSPECTOR
+ inline const EmbedderPreloadCallback& embedder_preload() const;
+ inline void set_embedder_preload(EmbedderPreloadCallback fn);
+
inline void set_process_exit_handler(
std::function<void(Environment*, int)>&& handler);
@@ -1102,6 +1106,7 @@ class Environment : public MemoryRetainer {
@@ -1094,6 +1097,7 @@ class Environment : public MemoryRetainer {
DefaultProcessExitHandler };
std::unique_ptr<Realm> principal_realm_ = nullptr;
@@ -167,55 +113,45 @@ index 36e8e7d960a95a9040ad963c79a7f66c89233c87..1b11c4243d18f14f4aaaad2683295fff
// Used by allocate_managed_buffer() and release_managed_buffer() to keep
// track of the BackingStore for a given pointer.
diff --git a/src/node.h b/src/node.h
index 26368061a909e6abc62a4cf261a5dbbd79404f1a..bb4065e33164c3ea762a27b71606ab4ed7b1b336 100644
index 26368061a909e6abc62a4cf261a5dbbd79404f1a..0dec1e311d7c00c2b830a0b2a6bde4336aebe68b 100644
--- a/src/node.h
+++ b/src/node.h
@@ -593,9 +593,21 @@ struct InspectorParentHandle {
virtual ~InspectorParentHandle();
};
@@ -630,13 +630,33 @@ struct StartExecutionCallbackInfo {
using StartExecutionCallback =
std::function<v8::MaybeLocal<v8::Value>(const StartExecutionCallbackInfo&)>;
+using EmbedderPreloadCallback =
+ std::function<void(Environment* env,
+ v8::Local<v8::Value> process,
+ v8::Local<v8::Value> require)>;
+
// TODO(addaleax): Maybe move per-Environment options parsing here.
// Returns nullptr when the Environment cannot be created e.g. there are
// pending JavaScript exceptions.
+//
+// The |preload| function will run before executing the entry point, which
+// is usually used by embedders to inject scripts. The function is executed
+// with preload(process, require), and the passed require function has access
+// to internal Node.js modules. The |preload| function is inherited by worker
+// threads and thus will run in work threads, so make sure the function is
+// thread-safe.
NODE_EXTERN Environment* CreateEnvironment(
IsolateData* isolate_data,
v8::Local<v8::Context> context,
@@ -603,7 +615,8 @@ NODE_EXTERN Environment* CreateEnvironment(
const std::vector<std::string>& exec_args,
EnvironmentFlags::Flags flags = EnvironmentFlags::kDefaultFlags,
ThreadId thread_id = {} /* allocates a thread id automatically */,
- std::unique_ptr<InspectorParentHandle> inspector_parent_handle = {});
+ std::unique_ptr<InspectorParentHandle> inspector_parent_handle = {},
+ EmbedderPreloadCallback preload = nullptr);
// Returns a handle that can be passed to `LoadEnvironment()`, making the
// child Environment accessible to the inspector as if it were a Node.js Worker.
diff --git a/src/node_main_instance.cc b/src/node_main_instance.cc
index a8661c3c2263fc62e55659310b8da12fc414361e..849442aa8c923808420cbc888befea7d3f1f4c1b 100644
--- a/src/node_main_instance.cc
+++ b/src/node_main_instance.cc
@@ -157,7 +157,8 @@ NodeMainInstance::CreateMainEnvironment(int* exit_code) {
exec_args_,
&(snapshot_data_->env_info),
EnvironmentFlags::kDefaultFlags,
- {}));
+ {},
+ nullptr));
context = Context::FromSnapshot(isolate_,
SnapshotData::kNodeMainContextIndex,
{DeserializeNodeInternalFields, env.get()})
+// Run initialization for the environment.
+//
+// The |preload| function, usually used by embedders to inject scripts,
+// will be run by Node.js before Node.js executes the entry point.
+// The function is guaranteed to run before the user land module loader running
+// any user code, so it is safe to assume that at this point, no user code has
+// been run yet.
+// The function will be executed with preload(process, require), and the passed
+// require function has access to internal Node.js modules. There is no
+// stability guarantee about the internals exposed to the internal require
+// function. Expect breakages when updating Node.js versions if the embedder
+// imports internal modules with the internal require function.
+// Worker threads created in the environment will also respect The |preload|
+// function, so make sure the function is thread-safe.
NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
Environment* env,
- StartExecutionCallback cb);
+ StartExecutionCallback cb,
+ EmbedderPreloadCallback preload = nullptr);
NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
Environment* env,
- const char* main_script_source_utf8);
+ const char* main_script_source_utf8,
+ EmbedderPreloadCallback preload = nullptr);
NODE_EXTERN void FreeEnvironment(Environment* env);
// Set a callback that is called when process.exit() is called from JS,
diff --git a/src/node_options.cc b/src/node_options.cc
index 365748f046f9d0f232d4f0ebc7b0c7f56bbd74e2..a076de0c5e577114a6166844ab3b4f02db8065ad 100644
--- a/src/node_options.cc
@@ -234,24 +170,28 @@ index 365748f046f9d0f232d4f0ebc7b0c7f56bbd74e2..a076de0c5e577114a6166844ab3b4f02
}
diff --git a/src/node_snapshotable.cc b/src/node_snapshotable.cc
index f70e6ddf4303f303d7ace859b257738fd6707853..e6eb9d8602193ee8823724061592ae2ac681a816 100644
index f70e6ddf4303f303d7ace859b257738fd6707853..3f89973349f03128ab77f7cf3902506ec79d1272 100644
--- a/src/node_snapshotable.cc
+++ b/src/node_snapshotable.cc
@@ -1462,6 +1462,13 @@ void SerializeSnapshotableObjects(Realm* realm,
@@ -1462,6 +1462,17 @@ void SerializeSnapshotableObjects(Realm* realm,
namespace mksnapshot {
+static void RunEmbedderPreload(const FunctionCallbackInfo<Value>& args) {
+void RunEmbedderPreload(const FunctionCallbackInfo<Value>& args) {
+ Environment* env = Environment::GetCurrent(args);
+ CHECK(env->embedder_preload());
+ CHECK_EQ(args.Length(), 2);
+ env->embedder_preload()(env, args[0], args[1]);
+ Local<Value> process_obj = args[0];
+ Local<Value> require_fn = args[1];
+ CHECK(process_obj->IsObject());
+ CHECK(require_fn->IsFunction());
+ env->embedder_preload()(env, process_obj, require_fn);
+}
+
void CompileSerializeMain(const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsString());
Local<String> filename = args[0].As<String>();
@@ -1515,6 +1522,7 @@ void Initialize(Local<Object> target,
@@ -1515,6 +1526,7 @@ void Initialize(Local<Object> target,
Local<Value> unused,
Local<Context> context,
void* priv) {
@@ -259,7 +199,7 @@ index f70e6ddf4303f303d7ace859b257738fd6707853..e6eb9d8602193ee8823724061592ae2a
SetMethod(context, target, "compileSerializeMain", CompileSerializeMain);
SetMethod(context, target, "setSerializeCallback", SetSerializeCallback);
SetMethod(context, target, "setDeserializeCallback", SetDeserializeCallback);
@@ -1525,6 +1533,7 @@ void Initialize(Local<Object> target,
@@ -1525,6 +1537,7 @@ void Initialize(Local<Object> target,
}
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
@@ -268,7 +208,7 @@ index f70e6ddf4303f303d7ace859b257738fd6707853..e6eb9d8602193ee8823724061592ae2a
registry->Register(SetSerializeCallback);
registry->Register(SetDeserializeCallback);
diff --git a/src/node_worker.cc b/src/node_worker.cc
index 6a49144ec4f2059fe75983609b0768e4c2b1817d..dc2eb247b011f9cb1945c173c49e029f068ef103 100644
index 6a49144ec4f2059fe75983609b0768e4c2b1817d..13b0445370c70cf3765a4af44336c16ac2e1035d 100644
--- a/src/node_worker.cc
+++ b/src/node_worker.cc
@@ -60,6 +60,7 @@ Worker::Worker(Environment* env,
@@ -279,16 +219,20 @@ index 6a49144ec4f2059fe75983609b0768e4c2b1817d..dc2eb247b011f9cb1945c173c49e029f
snapshot_data_(snapshot_data) {
Debug(this, "Creating new worker instance with thread id %llu",
thread_id_.id);
@@ -333,7 +334,8 @@ void Worker::Run() {
std::move(exec_argv_),
static_cast<EnvironmentFlags::Flags>(environment_flags_),
thread_id_,
- std::move(inspector_parent_handle_)));
+ std::move(inspector_parent_handle_),
+ std::move(embedder_preload_)));
if (is_stopped()) return;
CHECK_NOT_NULL(env_);
env_->set_env_vars(std::move(env_vars_));
@@ -354,8 +355,12 @@ void Worker::Run() {
}
Debug(this, "Created message port for worker %llu", thread_id_.id);
- if (LoadEnvironment(env_.get(), StartExecutionCallback{}).IsEmpty())
+ if (LoadEnvironment(env_.get(),
+ StartExecutionCallback{},
+ std::move(embedder_preload_))
+ .IsEmpty()) {
return;
+ }
Debug(this, "Loaded environment for worker %llu", thread_id_.id);
}
diff --git a/src/node_worker.h b/src/node_worker.h
index a77c416735a79feb3f54e40d72a98c8903a20ccd..deab68576f6330f8bcfb4703fd05dbb9c515e473 100644
--- a/src/node_worker.h
@@ -302,7 +246,7 @@ index a77c416735a79feb3f54e40d72a98c8903a20ccd..deab68576f6330f8bcfb4703fd05dbb9
// A raw flag that is used by creator and worker threads to
// sync up on pre-mature termination of worker - while in the
diff --git a/test/cctest/test_environment.cc b/test/cctest/test_environment.cc
index 09dcb1dccc1b28048c6300e2c23c2c40722272af..14a76a9baa7ca39a628553f730cde6c3c04c6be9 100644
index 09dcb1dccc1b28048c6300e2c23c2c40722272af..54460cd9ecf3c8bbf9927598fcbaf05f5937cf9a 100644
--- a/test/cctest/test_environment.cc
+++ b/test/cctest/test_environment.cc
@@ -740,3 +740,31 @@ TEST_F(EnvironmentTest, RequestInterruptAtExit) {
@@ -320,20 +264,20 @@ index 09dcb1dccc1b28048c6300e2c23c2c40722272af..14a76a9baa7ca39a628553f730cde6c3
+ v8::Local<v8::Value> require) {
+ CHECK(process->IsObject());
+ CHECK(require->IsFunction());
+ process.As<v8::Object>()->Set(
+ env->context(),
+ v8::String::NewFromUtf8Literal(env->isolate(), "prop"),
+ v8::String::NewFromUtf8Literal(env->isolate(), "preload")).Check();
+ process.As<v8::Object>()
+ ->Set(env->context(),
+ v8::String::NewFromUtf8Literal(env->isolate(), "prop"),
+ v8::String::NewFromUtf8Literal(env->isolate(), "preload"))
+ .Check();
+ };
+
+ std::unique_ptr<node::Environment, decltype(&node::FreeEnvironment)> env(
+ node::CreateEnvironment(isolate_data_, context, {}, {},
+ node::EnvironmentFlags::kDefaultFlags, {}, {},
+ preload),
+ node::CreateEnvironment(isolate_data_, context, {}, {}),
+ node::FreeEnvironment);
+
+ v8::Local<v8::Value> main_ret =
+ node::LoadEnvironment(env.get(), "return process.prop;").ToLocalChecked();
+ node::LoadEnvironment(env.get(), "return process.prop;", preload)
+ .ToLocalChecked();
+ node::Utf8Value main_ret_str(isolate_, main_ret);
+ EXPECT_EQ(std::string(*main_ret_str), "preload");
+}

View File

@@ -2,3 +2,7 @@ build_gn.patch
do_not_export_private_v8_symbols_on_windows.patch
fix_build_deprecated_attribute_for_older_msvc_versions.patch
chore_allow_customizing_microtask_policy_per_context.patch
merged_wasm_add_bounds_check_in_tier-up_of_wasm-to-js_wrapper.patch
merged_parser_fix_home_object_proxy_to_work_off-thread.patch
merged_wasm_check_for_type-definition_count_limit.patch
merged_runtime_recreate_enum_cache_on_map_update_if_any_previous.patch

View File

@@ -0,0 +1,276 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Shu-yu Guo <syg@chromium.org>
Date: Thu, 7 Mar 2024 14:55:28 -0800
Subject: Merged: [parser] Fix home object proxy to work off-thread
Because the home object has special scope lookup rules due to class
heritage position, VariableProxies of the home object are currently
directly created on the correct scope during parsing. However, during
off-thread parsing the main thread is parked, and the correct scope
may try to dereference a main-thread Handle.
This CL moves the logic into ResolveVariable instead, which happens
during postprocessing, with the main thread unparked.
Fixed: chromium:327740539
(cherry picked from commit 8f477f936c9b9e6b4c9f35a8ccc5e65bd4cb7f4e)
Change-Id: I16805ad35f5d70d1acadaf1f5440dfc159dbfa6c
Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/5363634
Reviewed-by: Deepti Gandluri <gdeepti@chromium.org>
Commit-Queue: Shu-yu Guo <syg@chromium.org>
Cr-Commit-Position: refs/branch-heads/12.2@{#44}
Cr-Branched-From: 6eb5a9616aa6f8c705217aeb7c7ab8c037a2f676-refs/heads/12.2.281@{#1}
Cr-Branched-From: 44cf56d850167c6988522f8981730462abc04bcc-refs/heads/main@{#91934}
diff --git a/src/ast/ast.h b/src/ast/ast.h
index cf9d52eeed67a3d7685916987b540950385f98ce..7bb30723607ec9a3cef9d45b032c3edfa55bdc9c 100644
--- a/src/ast/ast.h
+++ b/src/ast/ast.h
@@ -1534,6 +1534,12 @@ class VariableProxy final : public Expression {
bit_field_ = IsRemovedFromUnresolvedField::update(bit_field_, true);
}
+ bool is_home_object() const { return IsHomeObjectField::decode(bit_field_); }
+
+ void set_is_home_object() {
+ bit_field_ = IsHomeObjectField::update(bit_field_, true);
+ }
+
// Provides filtered access to the unresolved variable proxy threaded list.
struct UnresolvedNext {
static VariableProxy** filter(VariableProxy** t) {
@@ -1565,6 +1571,7 @@ class VariableProxy final : public Expression {
bit_field_ |= IsAssignedField::encode(false) |
IsResolvedField::encode(false) |
IsRemovedFromUnresolvedField::encode(false) |
+ IsHomeObjectField::encode(false) |
HoleCheckModeField::encode(HoleCheckMode::kElided);
}
@@ -1574,7 +1581,8 @@ class VariableProxy final : public Expression {
using IsResolvedField = IsAssignedField::Next<bool, 1>;
using IsRemovedFromUnresolvedField = IsResolvedField::Next<bool, 1>;
using IsNewTargetField = IsRemovedFromUnresolvedField::Next<bool, 1>;
- using HoleCheckModeField = IsNewTargetField::Next<HoleCheckMode, 1>;
+ using IsHomeObjectField = IsNewTargetField::Next<bool, 1>;
+ using HoleCheckModeField = IsHomeObjectField::Next<HoleCheckMode, 1>;
union {
const AstRawString* raw_name_; // if !is_resolved_
diff --git a/src/ast/scopes.cc b/src/ast/scopes.cc
index 672440a2b4b9ad6262c49be50d03377b413452a6..6dfcd45cf208e58a2fc0cd18ba3b115bae35a0d5 100644
--- a/src/ast/scopes.cc
+++ b/src/ast/scopes.cc
@@ -491,7 +491,6 @@ Scope* Scope::DeserializeScopeChain(IsolateT* isolate, Zone* zone,
if (cache_scope_found) {
outer_scope->set_deserialized_scope_uses_external_cache();
} else {
- DCHECK(!cache_scope_found);
cache_scope_found =
outer_scope->is_declaration_scope() && !outer_scope->is_eval_scope();
}
@@ -970,9 +969,14 @@ Variable* Scope::LookupInScopeInfo(const AstRawString* name, Scope* cache) {
DCHECK(!cache->deserialized_scope_uses_external_cache());
// The case where where the cache can be another scope is when the cache scope
// is the last scope that doesn't use an external cache.
+ //
+ // The one exception to this is when looking up the home object, which may
+ // skip multiple scopes that don't use an external cache (e.g., several arrow
+ // functions).
DCHECK_IMPLIES(
cache != this,
- cache->outer_scope()->deserialized_scope_uses_external_cache());
+ cache->outer_scope()->deserialized_scope_uses_external_cache() ||
+ cache->GetHomeObjectScope() == this);
DCHECK_NULL(cache->variables_.Lookup(name));
DisallowGarbageCollection no_gc;
@@ -2282,7 +2286,33 @@ Variable* Scope::LookupSloppyEval(VariableProxy* proxy, Scope* scope,
void Scope::ResolveVariable(VariableProxy* proxy) {
DCHECK(!proxy->is_resolved());
- Variable* var = Lookup<kParsedScope>(proxy, this, nullptr);
+ Variable* var;
+ if (V8_UNLIKELY(proxy->is_home_object())) {
+ // VariableProxies of the home object cannot be resolved like a normal
+ // variable. Consider the case of a super.property usage in heritage
+ // position:
+ //
+ // class C extends super.foo { m() { super.bar(); } }
+ //
+ // The super.foo property access is logically nested under C's class scope,
+ // which also has a home object due to its own method m's usage of
+ // super.bar(). However, super.foo must resolve super in C's outer scope.
+ //
+ // Because of the above, start resolving home objects directly at the home
+ // object scope instead of the current scope.
+ Scope* scope = GetDeclarationScope()->GetHomeObjectScope();
+ DCHECK_NOT_NULL(scope);
+ if (scope->scope_info_.is_null()) {
+ var = Lookup<kParsedScope>(proxy, scope, nullptr);
+ } else {
+ Scope* entry_cache = scope->deserialized_scope_uses_external_cache()
+ ? GetNonEvalDeclarationScope()
+ : scope;
+ var = Lookup<kDeserializedScope>(proxy, scope, nullptr, entry_cache);
+ }
+ } else {
+ var = Lookup<kParsedScope>(proxy, this, nullptr);
+ }
DCHECK_NOT_NULL(var);
ResolveTo(proxy, var);
}
@@ -2752,48 +2782,6 @@ int Scope::ContextLocalCount() const {
(is_function_var_in_context ? 1 : 0);
}
-VariableProxy* Scope::NewHomeObjectVariableProxy(AstNodeFactory* factory,
- const AstRawString* name,
- int start_pos) {
- // VariableProxies of the home object cannot be resolved like a normal
- // variable. Consider the case of a super.property usage in heritage position:
- //
- // class C extends super.foo { m() { super.bar(); } }
- //
- // The super.foo property access is logically nested under C's class scope,
- // which also has a home object due to its own method m's usage of
- // super.bar(). However, super.foo must resolve super in C's outer scope.
- //
- // Because of the above, home object VariableProxies are always made directly
- // on the Scope that needs the home object instead of the innermost scope.
- DCHECK(needs_home_object());
- if (!scope_info_.is_null()) {
- // This is a lazy compile, so the home object's context slot is already
- // known.
- Variable* home_object = variables_.Lookup(name);
- if (home_object == nullptr) {
- VariableLookupResult lookup_result;
- int index = scope_info_->ContextSlotIndex(name->string(), &lookup_result);
- DCHECK_GE(index, 0);
- bool was_added;
- home_object = variables_.Declare(zone(), this, name, lookup_result.mode,
- NORMAL_VARIABLE, lookup_result.init_flag,
- lookup_result.maybe_assigned_flag,
- IsStaticFlag::kNotStatic, &was_added);
- DCHECK(was_added);
- home_object->AllocateTo(VariableLocation::CONTEXT, index);
- }
- return factory->NewVariableProxy(home_object, start_pos);
- }
- // This is not a lazy compile. Add the unresolved home object VariableProxy to
- // the unresolved list of the home object scope, which is not necessarily the
- // innermost scope.
- VariableProxy* proxy =
- factory->NewVariableProxy(name, NORMAL_VARIABLE, start_pos);
- AddUnresolved(proxy);
- return proxy;
-}
-
bool IsComplementaryAccessorPair(VariableMode a, VariableMode b) {
switch (a) {
case VariableMode::kPrivateGetterOnly:
diff --git a/src/ast/scopes.h b/src/ast/scopes.h
index b4c2e8b2136813985231a722c6dbcd26e2c17336..751aaee3d11ecc0da71e2171dd42ed4b85d00219 100644
--- a/src/ast/scopes.h
+++ b/src/ast/scopes.h
@@ -603,10 +603,6 @@ class V8_EXPORT_PRIVATE Scope : public NON_EXPORTED_BASE(ZoneObject) {
needs_home_object_ = true;
}
- VariableProxy* NewHomeObjectVariableProxy(AstNodeFactory* factory,
- const AstRawString* name,
- int start_pos);
-
bool RemoveInnerScope(Scope* inner_scope) {
DCHECK_NOT_NULL(inner_scope);
if (inner_scope == inner_scope_) {
@@ -865,7 +861,7 @@ class V8_EXPORT_PRIVATE DeclarationScope : public Scope {
FunctionKind function_kind() const { return function_kind_; }
// Inform the scope that the corresponding code uses "super".
- Scope* RecordSuperPropertyUsage() {
+ void RecordSuperPropertyUsage() {
DCHECK(IsConciseMethod(function_kind()) ||
IsAccessorFunction(function_kind()) ||
IsClassConstructor(function_kind()));
@@ -873,7 +869,6 @@ class V8_EXPORT_PRIVATE DeclarationScope : public Scope {
Scope* home_object_scope = GetHomeObjectScope();
DCHECK_NOT_NULL(home_object_scope);
home_object_scope->set_needs_home_object();
- return home_object_scope;
}
bool uses_super_property() const { return uses_super_property_; }
diff --git a/src/parsing/parser-base.h b/src/parsing/parser-base.h
index af7add9aa8231233dffd5f04ca491b3f614c3f97..232a6bdae48d5d6300b53bfd05b42841d2eae664 100644
--- a/src/parsing/parser-base.h
+++ b/src/parsing/parser-base.h
@@ -3823,9 +3823,9 @@ ParserBase<Impl>::ParseSuperExpression() {
impl()->ReportMessage(MessageTemplate::kOptionalChainingNoSuper);
return impl()->FailureExpression();
}
- Scope* home_object_scope = scope->RecordSuperPropertyUsage();
+ scope->RecordSuperPropertyUsage();
UseThis();
- return impl()->NewSuperPropertyReference(home_object_scope, pos);
+ return impl()->NewSuperPropertyReference(pos);
}
// super() is only allowed in derived constructor. new super() is never
// allowed; it's reported as an error by
diff --git a/src/parsing/parser.cc b/src/parsing/parser.cc
index d42cd361d230de2b7da93a05785b2b721ff372cd..4c1ce5360f2b7f8a9c8a19fcee25e65b3a433db5 100644
--- a/src/parsing/parser.cc
+++ b/src/parsing/parser.cc
@@ -300,18 +300,17 @@ Expression* Parser::NewThrowError(Runtime::FunctionId id,
return factory()->NewThrow(call_constructor, pos);
}
-Expression* Parser::NewSuperPropertyReference(Scope* home_object_scope,
- int pos) {
+Expression* Parser::NewSuperPropertyReference(int pos) {
const AstRawString* home_object_name;
if (IsStatic(scope()->GetReceiverScope()->function_kind())) {
home_object_name = ast_value_factory_->dot_static_home_object_string();
} else {
home_object_name = ast_value_factory_->dot_home_object_string();
}
- return factory()->NewSuperPropertyReference(
- home_object_scope->NewHomeObjectVariableProxy(factory(), home_object_name,
- pos),
- pos);
+
+ VariableProxy* proxy = NewUnresolved(home_object_name, pos);
+ proxy->set_is_home_object();
+ return factory()->NewSuperPropertyReference(proxy, pos);
}
Expression* Parser::NewSuperCallReference(int pos) {
diff --git a/src/parsing/parser.h b/src/parsing/parser.h
index 8aede5d6a2cd38b2ad02fa2d7542ea8163c29aa9..0e92f0350b5989781bda0eeb9746cfa18cd5e179 100644
--- a/src/parsing/parser.h
+++ b/src/parsing/parser.h
@@ -798,7 +798,7 @@ class V8_EXPORT_PRIVATE Parser : public NON_EXPORTED_BASE(ParserBase<Parser>) {
return factory()->NewThisExpression(pos);
}
- Expression* NewSuperPropertyReference(Scope* home_object_scope, int pos);
+ Expression* NewSuperPropertyReference(int pos);
Expression* NewSuperCallReference(int pos);
Expression* NewTargetExpression(int pos);
Expression* ImportMetaExpression(int pos);
diff --git a/src/parsing/preparser.h b/src/parsing/preparser.h
index 6c4996bd06be782bd0f767a2bfb6d413cfc1ae82..2ca6b9ac407b0862d82be466eec624280b241b09 100644
--- a/src/parsing/preparser.h
+++ b/src/parsing/preparser.h
@@ -1536,8 +1536,7 @@ class PreParser : public ParserBase<PreParser> {
return PreParserExpression::This();
}
- V8_INLINE PreParserExpression
- NewSuperPropertyReference(Scope* home_object_scope, int pos) {
+ V8_INLINE PreParserExpression NewSuperPropertyReference(int pos) {
return PreParserExpression::Default();
}

View File

@@ -0,0 +1,50 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Darius Mercadier <dmercadier@chromium.org>
Date: Fri, 22 Mar 2024 17:55:04 +0100
Subject: Merged: [runtime] Recreate enum cache on map update if any previous
map had one
If any previous map in the transition tree had an enum cache, then we
recreate one when updating the map.
Bug: 330760873
(cherry picked from commit 807cf7d0b7d96212c98ed2119e07f9b2c6a23f61)
Change-Id: Ia9ea4cf17fef60166a0c037318eb539866aac37a
Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/5401859
Reviewed-by: Igor Sheludko <ishell@chromium.org>
Commit-Queue: Igor Sheludko <ishell@chromium.org>
Auto-Submit: Darius Mercadier <dmercadier@chromium.org>
Cr-Commit-Position: refs/branch-heads/12.2@{#52}
Cr-Branched-From: 6eb5a9616aa6f8c705217aeb7c7ab8c037a2f676-refs/heads/12.2.281@{#1}
Cr-Branched-From: 44cf56d850167c6988522f8981730462abc04bcc-refs/heads/main@{#91934}
diff --git a/src/objects/map-updater.cc b/src/objects/map-updater.cc
index 7d04b0641778365d6818cc362ed7c2f0e33071fd..b7b83ad235aee5d0703b9346d552c72b0812694f 100644
--- a/src/objects/map-updater.cc
+++ b/src/objects/map-updater.cc
@@ -1036,14 +1036,21 @@ MapUpdater::State MapUpdater::ConstructNewMap() {
Handle<Map> new_map =
Map::AddMissingTransitions(isolate_, split_map, new_descriptors);
+ bool had_any_enum_cache =
+ split_map->instance_descriptors(isolate_)
+ ->enum_cache()
+ ->keys()
+ ->length() > 0 ||
+ old_descriptors_->enum_cache()->keys()->length() > 0;
+
// Deprecated part of the transition tree is no longer reachable, so replace
// current instance descriptors in the "survived" part of the tree with
// the new descriptors to maintain descriptors sharing invariant.
split_map->ReplaceDescriptors(isolate_, *new_descriptors);
- // If the old descriptors had an enum cache, make sure the new ones do too.
- if (old_descriptors_->enum_cache()->keys()->length() > 0 &&
- new_map->NumberOfEnumerableProperties() > 0) {
+ // If the old descriptors had an enum cache (or if {split_map}'s descriptors
+ // had one), make sure the new ones do too.
+ if (had_any_enum_cache && new_map->NumberOfEnumerableProperties() > 0) {
FastKeyAccumulator::InitializeFastPropertyEnumCache(
isolate_, new_map, new_map->NumberOfEnumerableProperties());
}

View File

@@ -0,0 +1,37 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Andreas Haas <ahaas@chromium.org>
Date: Tue, 20 Feb 2024 16:27:22 +0100
Subject: Merged: [wasm] Add bounds check in tier-up of wasm-to-js wrapper
The entry index in the WasmApiFunctionRef was used to look for the given
WasmApiFunctionRef in the indirect function tables, but it was not
considered that the indirect function tables can have different lengths.
R=clemensb@chromium.org
Bug: 325893559
(cherry picked from commit 7330f46163e8a2c10a3d40ecbf554656f0ac55e8)
Change-Id: I52355890e21490c75566216985680c64e0b0db75
Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/5323850
Commit-Queue: Andreas Haas <ahaas@chromium.org>
Reviewed-by: Thibaud Michaud <thibaudm@chromium.org>
Cr-Commit-Position: refs/branch-heads/12.2@{#38}
Cr-Branched-From: 6eb5a9616aa6f8c705217aeb7c7ab8c037a2f676-refs/heads/12.2.281@{#1}
Cr-Branched-From: 44cf56d850167c6988522f8981730462abc04bcc-refs/heads/main@{#91934}
diff --git a/src/runtime/runtime-wasm.cc b/src/runtime/runtime-wasm.cc
index 5f711bc606633bd916356f0eca5799ce63760dbd..1077e6bb3ec359ef540987d030e244f1789aa14d 100644
--- a/src/runtime/runtime-wasm.cc
+++ b/src/runtime/runtime-wasm.cc
@@ -602,7 +602,8 @@ RUNTIME_FUNCTION(Runtime_TierUpWasmToJSWrapper) {
for (int table_index = 0; table_index < table_count; ++table_index) {
Handle<WasmIndirectFunctionTable> table =
instance->GetIndirectFunctionTable(isolate, table_index);
- if (table->refs()->get(entry_index) == *ref) {
+ if (entry_index < table->refs()->length() &&
+ table->refs()->get(entry_index) == *ref) {
table->targets()
->set<ExternalPointerTag::kWasmIndirectFunctionTargetTag>(
entry_index, isolate, wasm_code->instruction_start());

View File

@@ -0,0 +1,38 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Manos Koukoutos <manoskouk@chromium.org>
Date: Thu, 21 Mar 2024 11:38:08 +0100
Subject: Merged: [wasm] Check for type-definition count limit
(cherry picked from commit b852ad701db21d6db5b34e66f4ec1cdccd2ec4d4)
Bug: chromium:330575498
Change-Id: I395f0ed6d823b7d1e139da6551486e3627d65724
Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/5378419
Commit-Queue: Jakob Kummerow <jkummerow@chromium.org>
Reviewed-by: Jakob Kummerow <jkummerow@chromium.org>
Auto-Submit: Manos Koukoutos <manoskouk@chromium.org>
Cr-Original-Commit-Position: refs/heads/main@{#92941}
Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/5380190
Reviewed-by: Francis McCabe <fgm@chromium.org>
Commit-Queue: Adam Klein <adamk@chromium.org>
Reviewed-by: Adam Klein <adamk@chromium.org>
Cr-Commit-Position: refs/branch-heads/12.2@{#50}
Cr-Branched-From: 6eb5a9616aa6f8c705217aeb7c7ab8c037a2f676-refs/heads/12.2.281@{#1}
Cr-Branched-From: 44cf56d850167c6988522f8981730462abc04bcc-refs/heads/main@{#91934}
diff --git a/src/wasm/module-decoder-impl.h b/src/wasm/module-decoder-impl.h
index 5629ea1f1316b974e7858006f16b52669bdd2fd5..2738fc6c2a6a325dd2c4bbc5d6f9a58f10a9c94d 100644
--- a/src/wasm/module-decoder-impl.h
+++ b/src/wasm/module-decoder-impl.h
@@ -689,6 +689,11 @@ class ModuleDecoderImpl : public Decoder {
}
} else {
if (tracer_) tracer_->TypeOffset(pc_offset());
+ if (initial_size + 1 > kV8MaxWasmTypes) {
+ errorf(pc(), "Type definition count exceeds maximum %zu",
+ kV8MaxWasmTypes);
+ return;
+ }
// Similarly to above, we need to resize types for a group of size 1.
module_->types.resize(initial_size + 1);
module_->isorecursive_canonical_type_ids.resize(initial_size + 1);

View File

@@ -1,3 +1,4 @@
fix_fallback_to_x11_capturer_on_wayland.patch
fix_mark_pipewire_capturer_as_failed_after_session_is_closed.patch
fix_check_pipewire_init_before_creating_generic_capturer.patch
tighten_som_dchecks_to_checks_in_vp9_packetization.patch

View File

@@ -0,0 +1,103 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Erik=20Spr=C3=A5ng?= <sprang@webrtc.org>
Date: Fri, 19 Jan 2024 16:59:01 +0100
Subject: Tighten som DCHECKs to CHECKs in VP9 packetization.
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
(cherry picked from commit 6a992129fb0dede4a8fbdaf5de43abaf43c20299)
No-Try: True
Bug: chromium:1518991, chromium:1518994
Change-Id: I47f68ba6aaf4874fd952332bf213e3a1e0389268
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/335241
Auto-Submit: Erik Språng <sprang@webrtc.org>
Reviewed-by: Danil Chapovalov <danilchap@webrtc.org>
Commit-Queue: Danil Chapovalov <danilchap@webrtc.org>
Cr-Original-Commit-Position: refs/heads/main@{#41580}
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/338640
Reviewed-by: Mirko Bonadei <mbonadei@webrtc.org>
Commit-Queue: Erik Språng <sprang@webrtc.org>
Cr-Commit-Position: refs/branch-heads/6167@{#6}
Cr-Branched-From: ece5cb83715dea85617114b6d4e981fdee2623ba-refs/heads/main@{#41315}
diff --git a/modules/rtp_rtcp/source/rtp_format_vp9.cc b/modules/rtp_rtcp/source/rtp_format_vp9.cc
index 15e059e85c8968c8ed72efa6b17ac998b5597f45..9ad4aa97c34aabe761739045662adc6374e3dc69 100644
--- a/modules/rtp_rtcp/source/rtp_format_vp9.cc
+++ b/modules/rtp_rtcp/source/rtp_format_vp9.cc
@@ -94,8 +94,8 @@ size_t RefIndicesLength(const RTPVideoHeaderVP9& hdr) {
if (!hdr.inter_pic_predicted || !hdr.flexible_mode)
return 0;
- RTC_DCHECK_GT(hdr.num_ref_pics, 0U);
- RTC_DCHECK_LE(hdr.num_ref_pics, kMaxVp9RefPics);
+ RTC_CHECK_GT(hdr.num_ref_pics, 0U);
+ RTC_CHECK_LE(hdr.num_ref_pics, kMaxVp9RefPics);
return hdr.num_ref_pics;
}
@@ -123,9 +123,9 @@ size_t SsDataLength(const RTPVideoHeaderVP9& hdr) {
if (!hdr.ss_data_available)
return 0;
- RTC_DCHECK_GT(hdr.num_spatial_layers, 0U);
- RTC_DCHECK_LE(hdr.num_spatial_layers, kMaxVp9NumberOfSpatialLayers);
- RTC_DCHECK_LE(hdr.gof.num_frames_in_gof, kMaxVp9FramesInGof);
+ RTC_CHECK_GT(hdr.num_spatial_layers, 0U);
+ RTC_CHECK_LE(hdr.num_spatial_layers, kMaxVp9NumberOfSpatialLayers);
+ RTC_CHECK_LE(hdr.gof.num_frames_in_gof, kMaxVp9FramesInGof);
size_t length = 1; // V
if (hdr.spatial_layer_resolution_present) {
length += 4 * hdr.num_spatial_layers; // Y
@@ -136,7 +136,7 @@ size_t SsDataLength(const RTPVideoHeaderVP9& hdr) {
// N_G
length += hdr.gof.num_frames_in_gof; // T, U, R
for (size_t i = 0; i < hdr.gof.num_frames_in_gof; ++i) {
- RTC_DCHECK_LE(hdr.gof.num_ref_pics[i], kMaxVp9RefPics);
+ RTC_CHECK_LE(hdr.gof.num_ref_pics[i], kMaxVp9RefPics);
length += hdr.gof.num_ref_pics[i]; // R times
}
return length;
@@ -248,9 +248,9 @@ bool WriteRefIndices(const RTPVideoHeaderVP9& vp9,
// +-+-+-+-+-+-+-+-+ -| -|
//
bool WriteSsData(const RTPVideoHeaderVP9& vp9, rtc::BitBufferWriter* writer) {
- RTC_DCHECK_GT(vp9.num_spatial_layers, 0U);
- RTC_DCHECK_LE(vp9.num_spatial_layers, kMaxVp9NumberOfSpatialLayers);
- RTC_DCHECK_LE(vp9.gof.num_frames_in_gof, kMaxVp9FramesInGof);
+ RTC_CHECK_GT(vp9.num_spatial_layers, 0U);
+ RTC_CHECK_LE(vp9.num_spatial_layers, kMaxVp9NumberOfSpatialLayers);
+ RTC_CHECK_LE(vp9.gof.num_frames_in_gof, kMaxVp9FramesInGof);
bool g_bit = vp9.gof.num_frames_in_gof > 0;
RETURN_FALSE_ON_ERROR(writer->WriteBits(vp9.num_spatial_layers - 1, 3));
@@ -288,6 +288,8 @@ bool WriteSsData(const RTPVideoHeaderVP9& vp9, rtc::BitBufferWriter* writer) {
// current API to invoke SVC is not flexible enough.
RTPVideoHeaderVP9 RemoveInactiveSpatialLayers(
const RTPVideoHeaderVP9& original_header) {
+ RTC_CHECK_LE(original_header.num_spatial_layers,
+ kMaxVp9NumberOfSpatialLayers);
RTPVideoHeaderVP9 hdr(original_header);
if (original_header.first_active_layer == 0)
return hdr;
@@ -314,7 +316,7 @@ RtpPacketizerVp9::RtpPacketizerVp9(rtc::ArrayView<const uint8_t> payload,
header_size_(PayloadDescriptorLengthMinusSsData(hdr_)),
first_packet_extra_header_size_(SsDataLength(hdr_)),
remaining_payload_(payload) {
- RTC_DCHECK_EQ(hdr_.first_active_layer, 0);
+ RTC_CHECK_EQ(hdr_.first_active_layer, 0);
limits.max_payload_len -= header_size_;
limits.first_packet_reduction_len += first_packet_extra_header_size_;
@@ -357,8 +359,8 @@ bool RtpPacketizerVp9::NextPacket(RtpPacketToSend* packet) {
// Ensure end_of_picture is always set on top spatial layer when it is not
// dropped.
- RTC_DCHECK(hdr_.spatial_idx < hdr_.num_spatial_layers - 1 ||
- hdr_.end_of_picture);
+ RTC_CHECK(hdr_.spatial_idx < hdr_.num_spatial_layers - 1 ||
+ hdr_.end_of_picture);
packet->SetMarker(layer_end && hdr_.end_of_picture);
return true;

View File

@@ -3,19 +3,30 @@
import argparse
import json
import os
import warnings
from lib import git
from lib.patches import patch_from_dir
THREEWAY = "ELECTRON_USE_THREE_WAY_MERGE_FOR_PATCHES" in os.environ
def apply_patches(dirs):
threeway = os.environ.get("ELECTRON_USE_THREE_WAY_MERGE_FOR_PATCHES")
for patch_dir, repo in dirs.items():
if os.path.exists(repo):
git.import_patches(repo=repo, patch_data=patch_from_dir(patch_dir),
threeway=threeway is not None,
committer_name="Electron Scripts", committer_email="scripts@electron")
def apply_patches(target):
repo = target.get('repo')
if not os.path.exists(repo):
warnings.warn('repo not found: %s' % repo)
return
patch_dir = target.get('patch_dir')
git.import_patches(
committer_email="scripts@electron",
committer_name="Electron Scripts",
patch_data=patch_from_dir(patch_dir),
repo=repo,
threeway=THREEWAY,
)
def apply_config(config):
for target in config:
apply_patches(target)
def parse_args():
parser = argparse.ArgumentParser(description='Apply Electron patches')
@@ -26,9 +37,8 @@ def parse_args():
def main():
configs = parse_args().config
for config_json in configs:
apply_patches(json.load(config_json))
for config_json in parse_args().config:
apply_config(json.load(config_json))
if __name__ == '__main__':

View File

@@ -3,14 +3,27 @@
import argparse
import json
import os
import warnings
from lib import git
def export_patches(dirs, dry_run):
for patch_dir, repo in dirs.items():
if os.path.exists(repo):
git.export_patches(repo=repo, out_dir=patch_dir, dry_run=dry_run)
def export_patches(target, dry_run):
repo = target.get('repo')
if not os.path.exists(repo):
warnings.warn('repo not found: %s' % repo)
return
git.export_patches(
dry_run=dry_run,
grep=target.get('grep'),
out_dir=target.get('patch_dir'),
repo=repo
)
def export_config(config, dry_run):
for target in config:
export_patches(target, dry_run)
def parse_args():
@@ -28,7 +41,7 @@ def main():
configs = parse_args().config
dry_run = parse_args().dry_run
for config_json in configs:
export_patches(json.load(config_json), dry_run)
export_config(json.load(config_json), dry_run)
if __name__ == '__main__':

View File

@@ -10,13 +10,15 @@ def main(argv):
parser.add_argument("-o", "--output",
help="directory into which exported patches will be written",
required=True)
parser.add_argument("--grep",
help="only export patches matching a keyword")
parser.add_argument("patch_range",
nargs='?',
help="range of patches to export. Defaults to all commits since the "
"most recent tag or remote branch.")
args = parser.parse_args(argv)
git.export_patches('.', args.output, patch_range=args.patch_range)
git.export_patches('.', args.output, patch_range=args.patch_range, grep=args.grep)
if __name__ == '__main__':

View File

@@ -15,6 +15,12 @@ import re
import subprocess
import sys
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(SCRIPT_DIR)
from patches import PATCH_FILENAME_PREFIX, is_patch_location_line
UPSTREAM_HEAD='refs/patches/upstream-head'
def is_repo_root(path):
path_exists = os.path.exists(path)
@@ -77,14 +83,10 @@ def am(repo, patch_data, threeway=False, directory=None, exclude=None,
proc.returncode))
def import_patches(repo, **kwargs):
def import_patches(repo, ref=UPSTREAM_HEAD, **kwargs):
"""same as am(), but we save the upstream HEAD so we can refer to it when we
later export patches"""
update_ref(
repo=repo,
ref='refs/patches/upstream-head',
newvalue='HEAD'
)
update_ref(repo=repo, ref=ref, newvalue='HEAD')
am(repo=repo, **kwargs)
@@ -94,32 +96,18 @@ def update_ref(repo, ref, newvalue):
return subprocess.check_call(args)
def get_upstream_head(repo):
args = [
'git',
'-C',
repo,
'rev-parse',
'--verify',
'refs/patches/upstream-head',
]
def get_commit_for_ref(repo, ref):
args = ['git', '-C', repo, 'rev-parse', '--verify', ref]
return subprocess.check_output(args).decode('utf-8').strip()
def get_commit_count(repo, commit_range):
args = [
'git',
'-C',
repo,
'rev-list',
'--count',
commit_range
]
args = ['git', '-C', repo, 'rev-list', '--count', commit_range]
return int(subprocess.check_output(args).decode('utf-8').strip())
def guess_base_commit(repo):
def guess_base_commit(repo, ref):
"""Guess which commit the patches might be based on"""
try:
upstream_head = get_upstream_head(repo)
upstream_head = get_commit_for_ref(repo, ref)
num_commits = get_commit_count(repo, upstream_head + '..')
return [upstream_head, num_commits]
except subprocess.CalledProcessError:
@@ -183,6 +171,16 @@ def split_patches(patch_data):
patches[-1].append(line)
return patches
def filter_patches(patches, key):
"""Return patches that include the specified key"""
if key is None:
return patches
matches = []
for patch in patches:
if any(key in line for line in patch):
matches.append(patch)
continue
return matches
def munge_subject_to_filename(subject):
"""Derive a suitable filename from a commit's subject"""
@@ -195,8 +193,8 @@ def get_file_name(patch):
"""Return the name of the file to which the patch should be written"""
file_name = None
for line in patch:
if line.startswith('Patch-Filename: '):
file_name = line[len('Patch-Filename: '):]
if line.startswith(PATCH_FILENAME_PREFIX):
file_name = line[len(PATCH_FILENAME_PREFIX):]
break
# If no patch-filename header, munge the subject.
if not file_name:
@@ -209,19 +207,18 @@ def get_file_name(patch):
def join_patch(patch):
"""Joins and formats patch contents"""
return ''.join(remove_patch_filename(patch)).rstrip('\n') + '\n'
return ''.join(remove_patch_location(patch)).rstrip('\n') + '\n'
def remove_patch_filename(patch):
"""Strip out the Patch-Filename trailer from a patch's message body"""
def remove_patch_location(patch):
"""Strip out the patch location lines from a patch's message body"""
force_keep_next_line = False
n = len(patch)
for i, l in enumerate(patch):
is_patchfilename = l.startswith('Patch-Filename: ')
next_is_patchfilename = i < len(patch) - 1 and patch[i + 1].startswith(
'Patch-Filename: '
)
skip_line = is_patch_location_line(l)
skip_next = i < n - 1 and is_patch_location_line(patch[i + 1])
if not force_keep_next_line and (
is_patchfilename or (next_is_patchfilename and len(l.rstrip()) == 0)
skip_line or (skip_next and len(l.rstrip()) == 0)
):
pass # drop this line
else:
@@ -237,18 +234,24 @@ def to_utf8(patch):
return unicode(patch, "utf-8")
def export_patches(repo, out_dir, patch_range=None, dry_run=False):
def export_patches(repo, out_dir,
patch_range=None, ref=UPSTREAM_HEAD,
dry_run=False, grep=None):
if not os.path.exists(repo):
sys.stderr.write(
"Skipping patches in {} because it does not exist.\n".format(repo)
)
return
if patch_range is None:
patch_range, num_patches = guess_base_commit(repo)
patch_range, num_patches = guess_base_commit(repo, ref)
sys.stderr.write("Exporting {} patches in {} since {}\n".format(
num_patches, repo, patch_range[0:7]))
patch_data = format_patch(repo, patch_range)
patches = split_patches(patch_data)
if grep:
olen = len(patches)
patches = filter_patches(patches, grep)
sys.stderr.write("Exporting {} of {} patches\n".format(len(patches), olen))
try:
os.mkdir(out_dir)

View File

@@ -3,19 +3,27 @@
import codecs
import os
PATCH_DIR_PREFIX = "Patch-Dir: "
PATCH_FILENAME_PREFIX = "Patch-Filename: "
PATCH_LINE_PREFIXES = (PATCH_DIR_PREFIX, PATCH_FILENAME_PREFIX)
def is_patch_location_line(line):
return line.startswith(PATCH_LINE_PREFIXES)
def read_patch(patch_dir, patch_filename):
"""Read a patch from |patch_dir/filename| and amend the commit message with
metadata about the patch file it came from."""
ret = []
added_filename_line = False
added_patch_location = False
patch_path = os.path.join(patch_dir, patch_filename)
with codecs.open(patch_path, encoding='utf-8') as f:
for l in f.readlines():
line_has_correct_start = l.startswith('diff -') or l.startswith('---')
if not added_filename_line and line_has_correct_start:
ret.append('Patch-Filename: {}\n'.format(patch_filename))
added_filename_line = True
if not added_patch_location and line_has_correct_start:
ret.append('{}{}\n'.format(PATCH_DIR_PREFIX, patch_dir))
ret.append('{}{}\n'.format(PATCH_FILENAME_PREFIX, patch_filename))
added_patch_location = True
ret.append(l)
return ''.join(ret)

View File

@@ -258,10 +258,9 @@ const LINTERS = [
process.exit(1);
}
const config = JSON.parse(fs.readFileSync(patchesConfig, 'utf8'));
for (const key of Object.keys(config)) {
for (const target of JSON.parse(fs.readFileSync(patchesConfig, 'utf8'))) {
// The directory the config points to should exist
const targetPatchesDir = path.resolve(__dirname, '../../..', key);
const targetPatchesDir = path.resolve(__dirname, '../../..', target.patch_dir);
if (!fs.existsSync(targetPatchesDir)) {
console.error(
`target patch directory: "${targetPatchesDir}" does not exist`

View File

@@ -14,7 +14,9 @@ from lib.patches import patch_from_dir
def patched_file_paths(patches_config):
for patch_dir, repo in patches_config.items():
for target in patches_config:
patch_dir = target.get('patch_dir')
repo = target.get('repo')
for line in patch_from_dir(patch_dir).split("\n"):
if line.startswith("+++"):
yield posixpath.join(repo, line[6:])

View File

@@ -27,7 +27,9 @@ const getHeaders = (filePath: string, fileName: string) => {
if (!extension) {
throw new Error(`Failed to get headers for extensionless file: ${fileName}`);
}
console.log(`About to get size of ${filePath}`);
const size = fs.statSync(filePath).size;
console.log(`Got size of ${filePath}: ${size}`);
const options: Record<string, string> = {
json: 'text/json',
zip: 'application/zip',
@@ -46,10 +48,13 @@ const uploadUrl = `https://uploads.github.com/repos/electron/${targetRepo}/relea
let retry = 0;
function uploadToGitHub () {
console.log(`in uploadToGitHub for ${filePath}, ${fileName}`);
const fileData = fs.createReadStream(filePath);
console.log(`in uploadToGitHub, created readstream for ${filePath}`);
octokit.repos.uploadReleaseAsset({
url: uploadUrl,
headers: getHeaders(filePath, fileName),
data: fs.createReadStream(filePath) as any,
data: fileData as any,
name: fileName,
owner: 'electron',
repo: targetRepo,

View File

@@ -363,10 +363,13 @@ def upload_io_to_github(release, filename, filepath, version):
(filename))
script_path = os.path.join(
ELECTRON_DIR, 'script', 'release', 'uploaders', 'upload-to-github.ts')
upload_gh_output = execute([TS_NODE, script_path, filepath, filename,
str(release['id']), version])
upload_process = subprocess.Popen([TS_NODE, script_path, filepath, filename,
str(release['id']), version], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
if is_verbose_mode():
print(upload_gh_output)
for c in iter(lambda: upload_process.stdout.read(1), b""):
sys.stdout.buffer.write(c)
sys.stdout.flush()
def upload_sha256_checksum(version, file_path, key_prefix=None):

View File

@@ -5,6 +5,7 @@
#include "shell/app/electron_content_client.h"
#include <string>
#include <string_view>
#include <utility>
#include <vector>
@@ -105,12 +106,12 @@ bool IsWidevineAvailable(
}
#endif // BUILDFLAG(ENABLE_WIDEVINE)
void AppendDelimitedSwitchToVector(const base::StringPiece cmd_switch,
void AppendDelimitedSwitchToVector(const std::string_view cmd_switch,
std::vector<std::string>* append_me) {
auto* command_line = base::CommandLine::ForCurrentProcess();
auto switch_value = command_line->GetSwitchValueASCII(cmd_switch);
if (!switch_value.empty()) {
constexpr base::StringPiece delimiter(",", 1);
constexpr std::string_view delimiter{",", 1};
auto tokens =
base::SplitString(switch_value, delimiter, base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);

View File

@@ -7,6 +7,7 @@
#include <iostream>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include "base/apple/bundle_locations.h"
@@ -80,9 +81,9 @@ namespace {
const char kRelauncherProcess[] = "relauncher";
constexpr base::StringPiece kElectronDisableSandbox("ELECTRON_DISABLE_SANDBOX");
constexpr base::StringPiece kElectronEnableStackDumping(
"ELECTRON_ENABLE_STACK_DUMPING");
constexpr std::string_view kElectronDisableSandbox{"ELECTRON_DISABLE_SANDBOX"};
constexpr std::string_view kElectronEnableStackDumping{
"ELECTRON_ENABLE_STACK_DUMPING"};
// Returns true if this subprocess type needs the ResourceBundle initialized
// and resources loaded.

View File

@@ -7,6 +7,7 @@
#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
@@ -59,17 +60,16 @@ namespace {
// See https://nodejs.org/api/cli.html#cli_options
void ExitIfContainsDisallowedFlags(const std::vector<std::string>& argv) {
// Options that are unilaterally disallowed.
static constexpr auto disallowed =
base::MakeFixedFlatSetSorted<base::StringPiece>({
"--enable-fips",
"--force-fips",
"--openssl-config",
"--use-bundled-ca",
"--use-openssl-ca",
});
static constexpr auto disallowed = base::MakeFixedFlatSet<std::string_view>({
"--enable-fips",
"--force-fips",
"--openssl-config",
"--use-bundled-ca",
"--use-openssl-ca",
});
for (const auto& arg : argv) {
const auto key = base::StringPiece(arg).substr(0, arg.find('='));
const auto key = std::string_view{arg}.substr(0, arg.find('='));
if (disallowed.contains(key)) {
LOG(ERROR) << "The Node.js cli flag " << key
<< " is not supported in Electron";
@@ -259,8 +259,7 @@ int NodeMain(int argc, char* argv[]) {
env = node::CreateEnvironment(
isolate_data, isolate->GetCurrentContext(), result->args(),
result->exec_args(),
static_cast<node::EnvironmentFlags::Flags>(env_flags), {}, {},
&OnNodePreload);
static_cast<node::EnvironmentFlags::Flags>(env_flags));
CHECK_NE(nullptr, env);
node::SetIsolateUpForNode(isolate);
@@ -285,7 +284,7 @@ int NodeMain(int argc, char* argv[]) {
}
v8::HandleScope scope(isolate);
node::LoadEnvironment(env, node::StartExecutionCallback{});
node::LoadEnvironment(env, node::StartExecutionCallback{}, &OnNodePreload);
// Potential reasons we get Nothing here may include: the env
// is stopping, or the user hooks process.emit('exit').

View File

@@ -6,6 +6,7 @@
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
@@ -24,6 +25,9 @@
#include "chrome/browser/icon_manager.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths.h"
#include "components/proxy_config/proxy_config_dictionary.h"
#include "components/proxy_config/proxy_config_pref_names.h"
#include "components/proxy_config/proxy_prefs.h"
#include "content/browser/gpu/compositor_util.h" // nogncheck
#include "content/browser/gpu/gpu_data_manager_impl.h" // nogncheck
#include "content/public/browser/browser_accessibility_state.h"
@@ -247,7 +251,7 @@ struct Converter<JumpListCategory::Type> {
private:
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, JumpListCategory::Type>({
base::MakeFixedFlatMap<std::string_view, JumpListCategory::Type>({
{"custom", JumpListCategory::Type::kCustom},
{"frequent", JumpListCategory::Type::kFrequent},
{"recent", JumpListCategory::Type::kRecent},
@@ -407,7 +411,7 @@ struct Converter<net::SecureDnsMode> {
v8::Local<v8::Value> val,
net::SecureDnsMode* out) {
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, net::SecureDnsMode>({
base::MakeFixedFlatMap<std::string_view, net::SecureDnsMode>({
{"automatic", net::SecureDnsMode::kAutomatic},
{"off", net::SecureDnsMode::kOff},
{"secure", net::SecureDnsMode::kSecure},
@@ -433,9 +437,9 @@ IconLoader::IconSize GetIconSizeByString(const std::string& size) {
}
// Return the path constant from string.
int GetPathConstant(base::StringPiece name) {
int GetPathConstant(std::string_view name) {
// clang-format off
constexpr auto Lookup = base::MakeFixedFlatMapSorted<base::StringPiece, int>({
constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, int>({
{"appData", DIR_APP_DATA},
#if BUILDFLAG(IS_POSIX)
{"cache", base::DIR_CACHE},
@@ -1468,6 +1472,98 @@ void App::EnableSandbox(gin_helper::ErrorThrower thrower) {
command_line->AppendSwitch(switches::kEnableSandbox);
}
v8::Local<v8::Promise> App::SetProxy(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
gin_helper::Dictionary options;
args->GetNext(&options);
if (!Browser::Get()->is_ready()) {
promise.RejectWithErrorMessage(
"app.setProxy() can only be called after app is ready.");
return handle;
}
if (!g_browser_process->local_state()) {
promise.RejectWithErrorMessage(
"app.setProxy() failed due to internal error.");
return handle;
}
std::string mode, proxy_rules, bypass_list, pac_url;
options.Get("pacScript", &pac_url);
options.Get("proxyRules", &proxy_rules);
options.Get("proxyBypassRules", &bypass_list);
ProxyPrefs::ProxyMode proxy_mode = ProxyPrefs::MODE_FIXED_SERVERS;
if (!options.Get("mode", &mode)) {
// pacScript takes precedence over proxyRules.
if (!pac_url.empty()) {
proxy_mode = ProxyPrefs::MODE_PAC_SCRIPT;
}
} else if (!ProxyPrefs::StringToProxyMode(mode, &proxy_mode)) {
promise.RejectWithErrorMessage(
"Invalid mode, must be one of direct, auto_detect, pac_script, "
"fixed_servers or system");
return handle;
}
base::Value::Dict proxy_config;
switch (proxy_mode) {
case ProxyPrefs::MODE_DIRECT:
proxy_config = ProxyConfigDictionary::CreateDirect();
break;
case ProxyPrefs::MODE_SYSTEM:
proxy_config = ProxyConfigDictionary::CreateSystem();
break;
case ProxyPrefs::MODE_AUTO_DETECT:
proxy_config = ProxyConfigDictionary::CreateAutoDetect();
break;
case ProxyPrefs::MODE_PAC_SCRIPT:
proxy_config = ProxyConfigDictionary::CreatePacScript(pac_url, true);
break;
case ProxyPrefs::MODE_FIXED_SERVERS:
proxy_config =
ProxyConfigDictionary::CreateFixedServers(proxy_rules, bypass_list);
break;
default:
NOTIMPLEMENTED();
}
static_cast<BrowserProcessImpl*>(g_browser_process)
->in_memory_pref_store()
->SetValue(proxy_config::prefs::kProxy,
base::Value{std::move(proxy_config)},
WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
g_browser_process->system_network_context_manager()
->GetContext()
->ForceReloadProxyConfig(base::BindOnce(
gin_helper::Promise<void>::ResolvePromise, std::move(promise)));
return handle;
}
v8::Local<v8::Promise> App::ResolveProxy(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<std::string> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
GURL url;
args->GetNext(&url);
static_cast<BrowserProcessImpl*>(g_browser_process)
->GetResolveProxyHelper()
->ResolveProxy(
url, base::BindOnce(gin_helper::Promise<std::string>::ResolvePromise,
std::move(promise)));
return handle;
}
void App::SetUserAgentFallback(const std::string& user_agent) {
ElectronBrowserClient::Get()->SetUserAgent(user_agent);
}
@@ -1772,7 +1868,9 @@ gin::ObjectTemplateBuilder App::GetObjectTemplateBuilder(v8::Isolate* isolate) {
.SetProperty("userAgentFallback", &App::GetUserAgentFallback,
&App::SetUserAgentFallback)
.SetMethod("configureHostResolver", &ConfigureHostResolver)
.SetMethod("enableSandbox", &App::EnableSandbox);
.SetMethod("enableSandbox", &App::EnableSandbox)
.SetMethod("setProxy", &App::SetProxy)
.SetMethod("resolveProxy", &App::ResolveProxy);
}
const char* App::GetTypeName() {

View File

@@ -222,6 +222,8 @@ class App : public ElectronBrowserClient::Delegate,
void EnableSandbox(gin_helper::ErrorThrower thrower);
void SetUserAgentFallback(const std::string& user_agent);
std::string GetUserAgentFallback();
v8::Local<v8::Promise> SetProxy(gin::Arguments* args);
v8::Local<v8::Promise> ResolveProxy(gin::Arguments* args);
#if BUILDFLAG(IS_MAC)
void SetActivationPolicy(gin_helper::ErrorThrower thrower,

View File

@@ -8,6 +8,7 @@
#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include "content/public/browser/browser_task_traits.h"
@@ -261,7 +262,7 @@ class BaseWindow : public gin_helper::TrackableObject<BaseWindow>,
void RemoveFromParentChildWindows();
template <typename... Args>
void EmitEventSoon(base::StringPiece eventName) {
void EmitEventSoon(std::string_view eventName) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(base::IgnoreResult(&BaseWindow::Emit<Args...>),

View File

@@ -4,6 +4,8 @@
#include "shell/browser/api/electron_api_cookies.h"
#include <string>
#include <string_view>
#include <utility>
#include "base/time/time.h"
@@ -169,7 +171,7 @@ base::Time ParseTimeProperty(const absl::optional<double>& value) {
return base::Time::FromSecondsSinceUnixEpoch(*value);
}
base::StringPiece InclusionStatusToString(net::CookieInclusionStatus status) {
std::string_view InclusionStatusToString(net::CookieInclusionStatus status) {
if (status.HasExclusionReason(net::CookieInclusionStatus::EXCLUDE_HTTP_ONLY))
return "Failed to create httponly cookie";
if (status.HasExclusionReason(

View File

@@ -162,6 +162,10 @@ v8::Local<v8::Promise> DataPipeHolder::ReadAll(v8::Isolate* isolate) {
return handle;
}
const char* DataPipeHolder::GetTypeName() {
return "DataPipeHolder";
}
// static
gin::Handle<DataPipeHolder> DataPipeHolder::Create(
v8::Isolate* isolate,

View File

@@ -18,7 +18,9 @@ namespace electron::api {
// Retains reference to the data pipe.
class DataPipeHolder : public gin::Wrappable<DataPipeHolder> {
public:
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
const char* GetTypeName() override;
static gin::Handle<DataPipeHolder> Create(
v8::Isolate* isolate,

View File

@@ -22,41 +22,45 @@
- (id)init {
if ((self = [super init])) {
NSDistributedNotificationCenter* distCenter =
NSDistributedNotificationCenter* distributed_center =
[NSDistributedNotificationCenter defaultCenter];
// A notification that the screen was locked.
[distCenter addObserver:self
selector:@selector(onScreenLocked:)
name:@"com.apple.screenIsLocked"
object:nil];
[distributed_center addObserver:self
selector:@selector(onScreenLocked:)
name:@"com.apple.screenIsLocked"
object:nil];
// A notification that the screen was unlocked by the user.
[distCenter addObserver:self
selector:@selector(onScreenUnlocked:)
name:@"com.apple.screenIsUnlocked"
object:nil];
[distributed_center addObserver:self
selector:@selector(onScreenUnlocked:)
name:@"com.apple.screenIsUnlocked"
object:nil];
// A notification that the workspace posts before the machine goes to sleep.
[distCenter addObserver:self
selector:@selector(isSuspending:)
name:NSWorkspaceWillSleepNotification
object:nil];
[distributed_center addObserver:self
selector:@selector(isSuspending:)
name:NSWorkspaceWillSleepNotification
object:nil];
// A notification that the workspace posts when the machine wakes from
// sleep.
[distCenter addObserver:self
selector:@selector(isResuming:)
name:NSWorkspaceDidWakeNotification
object:nil];
[distributed_center addObserver:self
selector:@selector(isResuming:)
name:NSWorkspaceDidWakeNotification
object:nil];
NSNotificationCenter* shared_center =
[[NSWorkspace sharedWorkspace] notificationCenter];
// A notification that the workspace posts when the user session becomes
// active.
[distCenter addObserver:self
selector:@selector(onUserDidBecomeActive:)
name:NSWorkspaceSessionDidBecomeActiveNotification
object:nil];
[shared_center addObserver:self
selector:@selector(onUserDidBecomeActive:)
name:NSWorkspaceSessionDidBecomeActiveNotification
object:nil];
// A notification that the workspace posts when the user session becomes
// inactive.
[distCenter addObserver:self
selector:@selector(onUserDidResignActive:)
name:NSWorkspaceSessionDidResignActiveNotification
object:nil];
[shared_center addObserver:self
selector:@selector(onUserDidResignActive:)
name:NSWorkspaceSessionDidResignActiveNotification
object:nil];
}
return self;
}

View File

@@ -124,6 +124,10 @@ gin::ObjectTemplateBuilder PowerSaveBlocker::GetObjectTemplateBuilder(
.SetMethod("isStarted", &PowerSaveBlocker::IsStarted);
}
const char* PowerSaveBlocker::GetTypeName() {
return "PowerSaveBlocker";
}
} // namespace electron::api
namespace {

View File

@@ -20,10 +20,10 @@ class PowerSaveBlocker : public gin::Wrappable<PowerSaveBlocker> {
static gin::Handle<PowerSaveBlocker> Create(v8::Isolate* isolate);
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
static gin::WrapperInfo kWrapperInfo;
const char* GetTypeName() override;
// disable copy
PowerSaveBlocker(const PowerSaveBlocker&) = delete;

View File

@@ -4,6 +4,7 @@
#include "shell/browser/api/electron_api_protocol.h"
#include <string_view>
#include <vector>
#include "base/command_line.h"
@@ -193,7 +194,7 @@ const char* const kBuiltinSchemes[] = {
};
// Convert error code to string.
constexpr base::StringPiece ErrorCodeToString(ProtocolError error) {
constexpr std::string_view ErrorCodeToString(ProtocolError error) {
switch (error) {
case ProtocolError::kRegistered:
return "The scheme has been registered";

View File

@@ -5,6 +5,7 @@
#include "shell/browser/api/electron_api_screen.h"
#include <string>
#include <string_view>
#include "base/functional/bind.h"
#include "gin/dictionary.h"
@@ -49,13 +50,13 @@ std::vector<std::string> MetricsToArray(uint32_t metrics) {
}
void DelayEmit(Screen* screen,
base::StringPiece name,
const std::string_view name,
const display::Display& display) {
screen->Emit(name, display);
}
void DelayEmitWithMetrics(Screen* screen,
base::StringPiece name,
const std::string_view name,
const display::Display& display,
const std::vector<std::string>& metrics) {
screen->Emit(name, display, metrics);

View File

@@ -4,6 +4,7 @@
#include "shell/browser/api/electron_api_service_worker_context.h"
#include <string_view>
#include <utility>
#include "base/strings/string_number_conversions.h"
@@ -25,7 +26,7 @@ namespace electron::api {
namespace {
constexpr base::StringPiece MessageSourceToString(
constexpr std::string_view MessageSourceToString(
const blink::mojom::ConsoleMessageSource source) {
switch (source) {
case blink::mojom::ConsoleMessageSource::kXml:

View File

@@ -2,10 +2,12 @@
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <iomanip>
#include <string_view>
#include <dwmapi.h>
#include <windows.devices.enumeration.h>
#include <wrl/client.h>
#include <iomanip>
#include "shell/browser/api/electron_api_system_preferences.h"
@@ -98,39 +100,38 @@ std::string SystemPreferences::GetAccentColor() {
std::string SystemPreferences::GetColor(gin_helper::ErrorThrower thrower,
const std::string& color) {
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, int>({
{"3d-dark-shadow", COLOR_3DDKSHADOW},
{"3d-face", COLOR_3DFACE},
{"3d-highlight", COLOR_3DHIGHLIGHT},
{"3d-light", COLOR_3DLIGHT},
{"3d-shadow", COLOR_3DSHADOW},
{"active-border", COLOR_ACTIVEBORDER},
{"active-caption", COLOR_ACTIVECAPTION},
{"active-caption-gradient", COLOR_GRADIENTACTIVECAPTION},
{"app-workspace", COLOR_APPWORKSPACE},
{"button-text", COLOR_BTNTEXT},
{"caption-text", COLOR_CAPTIONTEXT},
{"desktop", COLOR_DESKTOP},
{"disabled-text", COLOR_GRAYTEXT},
{"highlight", COLOR_HIGHLIGHT},
{"highlight-text", COLOR_HIGHLIGHTTEXT},
{"hotlight", COLOR_HOTLIGHT},
{"inactive-border", COLOR_INACTIVEBORDER},
{"inactive-caption", COLOR_INACTIVECAPTION},
{"inactive-caption-gradient", COLOR_GRADIENTINACTIVECAPTION},
{"inactive-caption-text", COLOR_INACTIVECAPTIONTEXT},
{"info-background", COLOR_INFOBK},
{"info-text", COLOR_INFOTEXT},
{"menu", COLOR_MENU},
{"menu-highlight", COLOR_MENUHILIGHT},
{"menu-text", COLOR_MENUTEXT},
{"menubar", COLOR_MENUBAR},
{"scrollbar", COLOR_SCROLLBAR},
{"window", COLOR_WINDOW},
{"window-frame", COLOR_WINDOWFRAME},
{"window-text", COLOR_WINDOWTEXT},
});
static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, int>({
{"3d-dark-shadow", COLOR_3DDKSHADOW},
{"3d-face", COLOR_3DFACE},
{"3d-highlight", COLOR_3DHIGHLIGHT},
{"3d-light", COLOR_3DLIGHT},
{"3d-shadow", COLOR_3DSHADOW},
{"active-border", COLOR_ACTIVEBORDER},
{"active-caption", COLOR_ACTIVECAPTION},
{"active-caption-gradient", COLOR_GRADIENTACTIVECAPTION},
{"app-workspace", COLOR_APPWORKSPACE},
{"button-text", COLOR_BTNTEXT},
{"caption-text", COLOR_CAPTIONTEXT},
{"desktop", COLOR_DESKTOP},
{"disabled-text", COLOR_GRAYTEXT},
{"highlight", COLOR_HIGHLIGHT},
{"highlight-text", COLOR_HIGHLIGHTTEXT},
{"hotlight", COLOR_HOTLIGHT},
{"inactive-border", COLOR_INACTIVEBORDER},
{"inactive-caption", COLOR_INACTIVECAPTION},
{"inactive-caption-gradient", COLOR_GRADIENTINACTIVECAPTION},
{"inactive-caption-text", COLOR_INACTIVECAPTIONTEXT},
{"info-background", COLOR_INFOBK},
{"info-text", COLOR_INFOTEXT},
{"menu", COLOR_MENU},
{"menu-highlight", COLOR_MENUHILIGHT},
{"menu-text", COLOR_MENUTEXT},
{"menubar", COLOR_MENUBAR},
{"scrollbar", COLOR_SCROLLBAR},
{"window", COLOR_WINDOW},
{"window-frame", COLOR_WINDOWFRAME},
{"window-text", COLOR_WINDOWTEXT},
});
if (const auto* iter = Lookup.find(color); iter != Lookup.end())
return ToRGBAHex(color_utils::GetSysSkColor(iter->second));

View File

@@ -5,6 +5,7 @@
#include "shell/browser/api/electron_api_tray.h"
#include <string>
#include <string_view>
#include "base/containers/fixed_flat_map.h"
#include "gin/dictionary.h"
@@ -32,7 +33,7 @@ struct Converter<electron::TrayIcon::IconType> {
electron::TrayIcon::IconType* out) {
using Val = electron::TrayIcon::IconType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"custom", Val::kCustom},
{"error", Val::kError},
{"info", Val::kInfo},

View File

@@ -8,6 +8,7 @@
#include <memory>
#include <set>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
@@ -206,7 +207,7 @@ struct Converter<printing::mojom::MarginType> {
printing::mojom::MarginType* out) {
using Val = printing::mojom::MarginType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"custom", Val::kCustomMargins},
{"default", Val::kDefaultMargins},
{"none", Val::kNoMargins},
@@ -223,7 +224,7 @@ struct Converter<printing::mojom::DuplexMode> {
printing::mojom::DuplexMode* out) {
using Val = printing::mojom::DuplexMode;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"longEdge", Val::kLongEdge},
{"shortEdge", Val::kShortEdge},
{"simplex", Val::kSimplex},
@@ -270,7 +271,7 @@ struct Converter<content::SavePageType> {
content::SavePageType* out) {
using Val = content::SavePageType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML},
{"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML},
{"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML},
@@ -315,7 +316,7 @@ struct Converter<electron::api::WebContents::Type> {
electron::api::WebContents::Type* out) {
using Val = electron::api::WebContents::Type;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"backgroundPage", Val::kBackgroundPage},
{"browserView", Val::kBrowserView},
{"offscreen", Val::kOffScreen},
@@ -343,7 +344,7 @@ namespace electron::api {
namespace {
constexpr base::StringPiece CursorTypeToString(
constexpr std::string_view CursorTypeToString(
ui::mojom::CursorType cursor_type) {
switch (cursor_type) {
case ui::mojom::CursorType::kPointer:

View File

@@ -8,6 +8,7 @@
#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
@@ -365,7 +366,7 @@ class WebContents : public ExclusiveAccessContext,
// this.emit(name, new Event(sender, message), args...);
template <typename... Args>
bool EmitWithSender(base::StringPiece name,
bool EmitWithSender(const std::string_view name,
content::RenderFrameHost* frame,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
Args&&... args) {

View File

@@ -72,7 +72,17 @@ WebFrameMain* WebFrameMain::FromFrameTreeNodeId(int frame_tree_node_id) {
// static
WebFrameMain* WebFrameMain::FromRenderFrameHost(content::RenderFrameHost* rfh) {
return rfh ? FromFrameTreeNodeId(rfh->GetFrameTreeNodeId()) : nullptr;
if (!rfh)
return nullptr;
// TODO(codebytere): remove after refactoring away from FrameTreeNodeId as map
// key.
auto* ftn =
static_cast<content::RenderFrameHostImpl*>(rfh)->frame_tree_node();
if (!ftn)
return nullptr;
return FromFrameTreeNodeId(rfh->GetFrameTreeNodeId());
}
gin::WrapperInfo WebFrameMain::kWrapperInfo = {gin::kEmbedderNativeGin};
@@ -358,8 +368,9 @@ gin::Handle<WebFrameMain> WebFrameMain::New(v8::Isolate* isolate) {
// static
gin::Handle<WebFrameMain> WebFrameMain::From(v8::Isolate* isolate,
content::RenderFrameHost* rfh) {
if (rfh == nullptr)
if (!rfh)
return gin::Handle<WebFrameMain>();
auto* web_frame = FromRenderFrameHost(rfh);
if (web_frame)
return gin::CreateHandle(isolate, web_frame);
@@ -376,12 +387,14 @@ gin::Handle<WebFrameMain> WebFrameMain::From(v8::Isolate* isolate,
gin::Handle<WebFrameMain> WebFrameMain::FromOrNull(
v8::Isolate* isolate,
content::RenderFrameHost* rfh) {
if (rfh == nullptr)
if (!rfh)
return gin::Handle<WebFrameMain>();
auto* web_frame = FromRenderFrameHost(rfh);
if (web_frame)
return gin::CreateHandle(isolate, web_frame);
return gin::Handle<WebFrameMain>();
if (!web_frame)
return gin::Handle<WebFrameMain>();
return gin::CreateHandle(isolate, web_frame);
}
// static

View File

@@ -6,6 +6,7 @@
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include "base/containers/contains.h"
@@ -33,7 +34,7 @@
#include "shell/common/gin_helper/dictionary.h"
static constexpr auto ResourceTypes =
base::MakeFixedFlatMapSorted<base::StringPiece,
base::MakeFixedFlatMapSorted<std::string_view,
extensions::WebRequestResourceType>({
{"cspReport", extensions::WebRequestResourceType::CSP_REPORT},
{"font", extensions::WebRequestResourceType::FONT},
@@ -77,7 +78,7 @@ struct UserData : public base::SupportsUserData::Data {
raw_ptr<WebRequest> data;
};
extensions::WebRequestResourceType ParseResourceType(base::StringPiece value) {
extensions::WebRequestResourceType ParseResourceType(std::string_view value) {
if (const auto* iter = ResourceTypes.find(value); iter != ResourceTypes.end())
return iter->second;

View File

@@ -24,8 +24,6 @@ namespace electron::api {
class WebRequest : public gin::Wrappable<WebRequest>, public WebRequestAPI {
public:
static gin::WrapperInfo kWrapperInfo;
// Return the WebRequest object attached to |browser_context|, create if there
// is no one.
// Note that the lifetime of WebRequest object is managed by Session, instead
@@ -44,6 +42,7 @@ class WebRequest : public gin::Wrappable<WebRequest>, public WebRequestAPI {
content::BrowserContext* browser_context);
// gin::Wrappable:
static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
const char* GetTypeName() override;

View File

@@ -53,9 +53,9 @@ class MessagePort : public gin::Wrappable<MessagePort>,
bool* threw_exception);
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
static gin::WrapperInfo kWrapperInfo;
const char* GetTypeName() override;
private:

View File

@@ -37,6 +37,7 @@
#include "net/proxy_resolution/proxy_config_with_annotation.h"
#include "services/device/public/cpp/geolocation/geolocation_manager.h"
#include "services/network/public/cpp/network_switches.h"
#include "shell/browser/net/resolve_proxy_helper.h"
#include "shell/common/electron_paths.h"
#include "shell/common/thread_restrictions.h"
@@ -100,9 +101,9 @@ void BrowserProcessImpl::PostEarlyInitialization() {
OSCrypt::RegisterLocalPrefs(pref_registry.get());
#endif
auto pref_store = base::MakeRefCounted<ValueMapPrefStore>();
ApplyProxyModeFromCommandLine(pref_store.get());
prefs_factory.set_command_line_prefs(std::move(pref_store));
in_memory_pref_store_ = base::MakeRefCounted<ValueMapPrefStore>();
ApplyProxyModeFromCommandLine(in_memory_pref_store());
prefs_factory.set_command_line_prefs(in_memory_pref_store());
// Only use a persistent prefs store when cookie encryption is enabled as that
// is the only key that needs it
@@ -316,6 +317,14 @@ const std::string& BrowserProcessImpl::GetSystemLocale() const {
return system_locale_;
}
electron::ResolveProxyHelper* BrowserProcessImpl::GetResolveProxyHelper() {
if (!resolve_proxy_helper_) {
resolve_proxy_helper_ = base::MakeRefCounted<electron::ResolveProxyHelper>(
system_network_context_manager()->GetContext());
}
return resolve_proxy_helper_.get();
}
#if BUILDFLAG(IS_LINUX)
void BrowserProcessImpl::SetLinuxStorageBackend(
os_crypt::SelectedLinuxBackend selected_backend) {

View File

@@ -31,6 +31,10 @@ namespace printing {
class PrintJobManager;
}
namespace electron {
class ResolveProxyHelper;
}
// Empty definition for std::unique_ptr, rather than a forward declaration
class BackgroundModeManager {};
@@ -53,9 +57,9 @@ class BrowserProcessImpl : public BrowserProcess {
void PreMainMessageLoopRun();
void PostDestroyThreads() {}
void PostMainMessageLoopRun();
void SetSystemLocale(const std::string& locale);
const std::string& GetSystemLocale() const;
electron::ResolveProxyHelper* GetResolveProxyHelper();
#if BUILDFLAG(IS_LINUX)
void SetLinuxStorageBackend(os_crypt::SelectedLinuxBackend selected_backend);
@@ -121,6 +125,10 @@ class BrowserProcessImpl : public BrowserProcess {
printing::PrintJobManager* print_job_manager() override;
StartupData* startup_data() override;
ValueMapPrefStore* in_memory_pref_store() const {
return in_memory_pref_store_.get();
}
private:
void CreateNetworkQualityObserver();
void CreateOSCryptAsync();
@@ -137,6 +145,8 @@ class BrowserProcessImpl : public BrowserProcess {
#endif
embedder_support::OriginTrialsSettingsStorage origin_trials_settings_storage_;
scoped_refptr<ValueMapPrefStore> in_memory_pref_store_;
scoped_refptr<electron::ResolveProxyHelper> resolve_proxy_helper_;
std::unique_ptr<network::NetworkQualityTracker> network_quality_tracker_;
std::unique_ptr<
network::NetworkQualityTracker::RTTAndThroughputEstimatesObserver>

View File

@@ -505,7 +505,8 @@ ElectronBrowserContext::GetReduceAcceptLanguageControllerDelegate() {
ResolveProxyHelper* ElectronBrowserContext::GetResolveProxyHelper() {
if (!resolve_proxy_helper_) {
resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this);
resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(
GetDefaultStoragePartition()->GetNetworkContext());
}
return resolve_proxy_helper_.get();
}

View File

@@ -4,6 +4,8 @@
#include "shell/browser/electron_browser_main_parts.h"
#include <string_view>
#include "base/command_line.h"
#include "base/environment.h"
#include "ui/ozone/public/ozone_switches.h"
@@ -15,8 +17,8 @@
#include "shell/common/thread_restrictions.h"
#endif
constexpr base::StringPiece kElectronOzonePlatformHint(
"ELECTRON_OZONE_PLATFORM_HINT");
constexpr std::string_view kElectronOzonePlatformHint{
"ELECTRON_OZONE_PLATFORM_HINT"};
#if BUILDFLAG(OZONE_PLATFORM_WAYLAND)

View File

@@ -5,6 +5,7 @@
#ifndef ELECTRON_SHELL_BROWSER_EVENT_EMITTER_MIXIN_H_
#define ELECTRON_SHELL_BROWSER_EVENT_EMITTER_MIXIN_H_
#include <string_view>
#include <utility>
#include "gin/handle.h"
@@ -25,7 +26,7 @@ class EventEmitterMixin {
// this.emit(name, new Event(), args...);
// Returns true if event.preventDefault() was called during processing.
template <typename... Args>
bool Emit(base::StringPiece name, Args&&... args) {
bool Emit(const std::string_view name, Args&&... args) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> wrapper;
@@ -39,7 +40,7 @@ class EventEmitterMixin {
// this.emit(name, args...);
template <typename... Args>
void EmitWithoutEvent(base::StringPiece name, Args&&... args) {
void EmitWithoutEvent(const std::string_view name, Args&&... args) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> wrapper;

View File

@@ -6,6 +6,7 @@
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include "base/files/file_path.h"
@@ -93,7 +94,7 @@ void ElectronExtensionSystem::InitForRegularProfile(bool extensions_enabled) {
}
std::unique_ptr<base::Value::Dict> ParseManifest(
base::StringPiece manifest_contents) {
const std::string_view manifest_contents) {
JSONStringValueDeserializer deserializer(manifest_contents);
std::unique_ptr<base::Value> manifest =
deserializer.Deserialize(nullptr, nullptr);

View File

@@ -6,6 +6,10 @@
#include <utility>
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include <string_view>
#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/strings/string_util.h"
@@ -32,7 +36,6 @@
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "base/containers/fixed_flat_set.h"
#include "base/strings/string_piece.h"
#include "extensions/common/constants.h"
#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
@@ -188,7 +191,7 @@ bool HidChooserContext::HasDevicePermission(
bool HidChooserContext::IsFidoAllowedForOrigin(const url::Origin& origin) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
static constexpr auto kPrivilegedExtensionIds =
base::MakeFixedFlatSet<base::StringPiece>({
base::MakeFixedFlatSet<std::string_view>({
"ckcendljdlmgnhghiaomidhiiclmapok", // gnubbyd-v3 dev
"lfboplenmmjcmpbkeemecobbadnmpfhi", // gnubbyd-v3 prod
});

View File

@@ -763,6 +763,11 @@ int NativeWindow::NonClientHitTest(const gfx::Point& point) {
}
#endif
// This is to disable dragging in HTML5 full screen mode.
// Details: https://github.com/electron/electron/issues/41002
if (GetWidget()->IsFullscreen())
return HTNOWHERE;
for (auto* provider : draggable_region_providers_) {
int hit = provider->NonClientHitTest(point);
if (hit != HTNOWHERE)

View File

@@ -447,11 +447,14 @@ void NativeWindowMac::Close() {
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
// window_ could be nil after performClose.
bool should_notify = is_modal() && parent() && IsVisible();
[window_ performClose:nil];
// Closing a sheet doesn't trigger windowShouldClose,
// so we need to manually call it ourselves here.
if (is_modal() && parent() && IsVisible()) {
if (should_notify) {
NotifyWindowCloseButtonClicked();
}
}

View File

@@ -7,6 +7,7 @@
#include <list>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include "base/containers/fixed_flat_map.h"
@@ -48,7 +49,7 @@ struct Converter<electron::ProtocolType> {
electron::ProtocolType* out) {
using Val = electron::ProtocolType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
// note "free" is internal type, not allowed to be passed from user
{"buffer", Val::kBuffer},
{"file", Val::kFile},

View File

@@ -4,6 +4,7 @@
#include "shell/browser/net/node_stream_loader.h"
#include <string_view>
#include <utility>
#include "mojo/public/cpp/system/string_data_source.h"
@@ -135,8 +136,8 @@ void NodeStreamLoader::ReadMore() {
is_reading_ = false;
is_writing_ = true;
producer_->Write(std::make_unique<mojo::StringDataSource>(
base::StringPiece(node::Buffer::Data(buffer),
node::Buffer::Length(buffer)),
std::string_view{node::Buffer::Data(buffer),
node::Buffer::Length(buffer)},
mojo::StringDataSource::AsyncWritingMode::
STRING_STAYS_VALID_UNTIL_COMPLETION),
base::BindOnce(&NodeStreamLoader::DidWrite, weak));

View File

@@ -8,19 +8,17 @@
#include "base/functional/bind.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "net/base/network_anonymization_key.h"
#include "net/proxy_resolution/proxy_info.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "shell/browser/electron_browser_context.h"
using content::BrowserThread;
namespace electron {
ResolveProxyHelper::ResolveProxyHelper(ElectronBrowserContext* browser_context)
: browser_context_(browser_context) {}
ResolveProxyHelper::ResolveProxyHelper(
network::mojom::NetworkContext* network_context)
: network_context_(network_context) {}
ResolveProxyHelper::~ResolveProxyHelper() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -54,11 +52,9 @@ void ResolveProxyHelper::StartPendingRequest() {
receiver_.set_disconnect_handler(
base::BindOnce(&ResolveProxyHelper::OnProxyLookupComplete,
base::Unretained(this), net::ERR_ABORTED, absl::nullopt));
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->LookUpProxyForURL(pending_requests_.front().url,
net::NetworkAnonymizationKey(),
std::move(proxy_lookup_client));
network_context_->LookUpProxyForURL(pending_requests_.front().url,
net::NetworkAnonymizationKey(),
std::move(proxy_lookup_client));
}
void ResolveProxyHelper::OnProxyLookupComplete(

View File

@@ -11,21 +11,20 @@
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/public/mojom/proxy_lookup_client.mojom.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/gurl.h"
namespace electron {
class ElectronBrowserContext;
class ResolveProxyHelper
: public base::RefCountedThreadSafe<ResolveProxyHelper>,
network::mojom::ProxyLookupClient {
public:
using ResolveProxyCallback = base::OnceCallback<void(std::string)>;
explicit ResolveProxyHelper(ElectronBrowserContext* browser_context);
explicit ResolveProxyHelper(network::mojom::NetworkContext* network_context);
void ResolveProxy(const GURL& url, ResolveProxyCallback callback);
@@ -71,7 +70,7 @@ class ResolveProxyHelper
mojo::Receiver<network::mojom::ProxyLookupClient> receiver_{this};
// Weak Ref
raw_ptr<ElectronBrowserContext> browser_context_;
raw_ptr<network::mojom::NetworkContext> network_context_ = nullptr;
};
} // namespace electron

View File

@@ -159,21 +159,21 @@ void LibnotifyNotification::Show(const NotificationOptions& options) {
void LibnotifyNotification::Dismiss() {
if (!notification_) {
Destroy();
return;
}
GError* error = nullptr;
on_dismissing_ = true;
libnotify_loader_.notify_notification_close(notification_, &error);
if (error) {
log_and_clear_error(error, "notify_notification_close");
Destroy();
}
on_dismissing_ = false;
}
void LibnotifyNotification::OnNotificationClosed(
NotifyNotification* notification) {
NotificationDismissed();
NotificationDismissed(!on_dismissing_);
}
void LibnotifyNotification::OnNotificationView(NotifyNotification* notification,

View File

@@ -33,6 +33,7 @@ class LibnotifyNotification : public Notification {
RAW_PTR_EXCLUSION NotifyNotification* notification_ = nullptr;
ScopedGSignal signal_;
bool on_dismissing_ = false;
};
} // namespace electron

View File

@@ -93,6 +93,9 @@ api::Session* SerialChooserController::GetSession() {
void SerialChooserController::OnPortAdded(
const device::mojom::SerialPortInfo& port) {
if (!FilterMatchesAny(port))
return;
ports_.push_back(port.Clone());
api::Session* session = GetSession();
if (session) {

View File

@@ -28,6 +28,7 @@
#include "net/socket/stream_socket.h"
#include "net/socket/tcp_server_socket.h"
#include "shell/browser/browser.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/common/electron_paths.h"
#include "third_party/inspector_protocol/crdtp/dispatch.h"
#include "ui/base/resource/resource_bundle.h"
@@ -139,4 +140,8 @@ bool DevToolsManagerDelegate::HasBundledFrontendResources() {
return true;
}
content::BrowserContext* DevToolsManagerDelegate::GetDefaultBrowserContext() {
return ElectronBrowserContext::From("", false);
}
} // namespace electron

View File

@@ -10,6 +10,10 @@
#include "base/compiler_specific.h"
#include "content/public/browser/devtools_manager_delegate.h"
namespace content {
class BrowserContext;
}
namespace electron {
class DevToolsManagerDelegate : public content::DevToolsManagerDelegate {
@@ -33,6 +37,7 @@ class DevToolsManagerDelegate : public content::DevToolsManagerDelegate {
TargetType target_type) override;
std::string GetDiscoveryPageHTML() override;
bool HasBundledFrontendResources() override;
content::BrowserContext* GetDefaultBrowserContext() override;
};
} // namespace electron

View File

@@ -5,6 +5,7 @@
#include "shell/browser/ui/file_dialog.h"
#include <string>
#include <string_view>
#include <utility>
#include <vector>
@@ -441,7 +442,7 @@ void SaveDialogCompletion(int chosen,
dict.Set("canceled", true);
dict.Set("filePath", base::FilePath());
#if IS_MAS_BUILD()
dict.Set("bookmark", base::StringPiece());
dict.Set("bookmark", std::string_view{});
#endif
} else {
std::string path = base::SysNSStringToUTF8([[dialog URL] path]);

View File

@@ -6,6 +6,7 @@
#include "shell/browser/ui/inspectable_web_contents.h"
#include <memory>
#include <string_view>
#include <utility>
#include "base/base64.h"
@@ -950,8 +951,8 @@ void InspectableWebContents::DispatchProtocolMessage(
if (!frontend_loaded_)
return;
base::StringPiece str_message(reinterpret_cast<const char*>(message.data()),
message.size());
const std::string_view str_message{
reinterpret_cast<const char*>(message.data()), message.size()};
if (str_message.length() < kMaxMessageChunkSize) {
CallClientFunction("DevToolsAPI", "dispatchMessage",
base::Value(std::string(str_message)));

View File

@@ -156,36 +156,26 @@ void WinCaptionButtonContainer::UpdateBackground() {
}
void WinCaptionButtonContainer::UpdateButtons() {
const bool is_maximized = frame_view_->frame()->IsMaximized();
restore_button_->SetVisible(is_maximized);
maximize_button_->SetVisible(!is_maximized);
const bool minimizable = frame_view_->window()->IsMinimizable();
minimize_button_->SetEnabled(minimizable);
minimize_button_->SetVisible(minimizable);
// In touch mode, windows cannot be taken out of fullscreen or tiled mode, so
// the maximize/restore button should be disabled.
const bool is_touch = ui::TouchUiController::Get()->touch_ui();
restore_button_->SetEnabled(!is_touch);
const bool is_maximized = frame_view_->frame()->IsMaximized();
const bool maximizable = frame_view_->window()->IsMaximizable();
restore_button_->SetVisible(is_maximized && maximizable);
maximize_button_->SetVisible(!is_maximized && maximizable);
// In touch mode, windows cannot be taken out of fullscreen or tiled mode, so
// the maximize/restore button should be disabled, unless the window is not
// maximized.
const bool maximizable = frame_view_->window()->IsMaximizable();
maximize_button_->SetEnabled(!(is_touch && is_maximized) && maximizable);
const bool is_touch = ui::TouchUiController::Get()->touch_ui();
restore_button_->SetEnabled(!is_touch);
maximize_button_->SetEnabled(!is_touch || !is_maximized);
// If the window isn't closable, the close button should be disabled.
const bool closable = frame_view_->window()->IsClosable();
close_button_->SetEnabled(closable);
// If all three of closable, maximizable, and minimizable are disabled,
// Windows natively only shows the disabled closable button. Copy that
// behavior here.
if (!maximizable && !closable && !minimizable) {
minimize_button_->SetVisible(false);
maximize_button_->SetVisible(false);
}
InvalidateLayout();
}
} // namespace electron

View File

@@ -4,6 +4,7 @@
#include "shell/browser/usb/electron_usb_delegate.h"
#include <string_view>
#include <utility>
#include "base/containers/contains.h"
@@ -45,7 +46,7 @@ electron::UsbChooserContext* GetChooserContext(
// These extensions can claim the smart card USB class and automatically gain
// permissions for devices that have an interface with this class.
constexpr auto kSmartCardPrivilegedExtensionIds =
base::MakeFixedFlatSetSorted<base::StringPiece>({
base::MakeFixedFlatSetSorted<std::string_view>({
// Smart Card Connector Extension and its Beta version, see
// crbug.com/1233881.
"khpfeaanjngmcnplbdlpegiifgpfgdco",

View File

@@ -4,6 +4,7 @@
#include "shell/browser/web_contents_permission_helper.h"
#include <string_view>
#include <utility>
#include "content/public/browser/browser_context.h"
@@ -17,7 +18,7 @@
namespace {
constexpr base::StringPiece MediaStreamTypeToString(
constexpr std::string_view MediaStreamTypeToString(
blink::mojom::MediaStreamType type) {
switch (type) {
case blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE:

View File

@@ -6,6 +6,7 @@
#include <algorithm>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
@@ -45,7 +46,7 @@ struct Converter<blink::mojom::AutoplayPolicy> {
blink::mojom::AutoplayPolicy* out) {
using Val = blink::mojom::AutoplayPolicy;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"document-user-activation-required",
Val::kDocumentUserActivationRequired},
{"no-user-gesture-required", Val::kNoUserGestureRequired},
@@ -62,7 +63,7 @@ struct Converter<blink::mojom::V8CacheOptions> {
blink::mojom::V8CacheOptions* out) {
using Val = blink::mojom::V8CacheOptions;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"bypassHeatCheck", Val::kCodeWithoutHeatCheck},
{"bypassHeatCheckAndEagerCompile", Val::kFullCodeWithoutHeatCheck},
{"code", Val::kCode},

View File

@@ -74,6 +74,7 @@ bool WebContentsZoomController::SetZoomLevel(double level) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
content::NavigationEntry* entry =
web_contents()->GetController().GetLastCommittedEntry();
// Cannot zoom in disabled mode. Also, don't allow changing zoom level on
// a crashed tab, an error page or an interstitial page.
if (zoom_mode_ == ZOOM_MODE_DISABLED ||
@@ -90,7 +91,7 @@ bool WebContentsZoomController::SetZoomLevel(double level) {
zoom_level_ = level;
ZoomChangedEventData zoom_change_data(web_contents(), old_zoom_level,
zoom_level_, false /* temporary */,
zoom_level_, true /* temporary */,
zoom_mode_);
for (auto& observer : observers_)
observer.OnZoomChanged(zoom_change_data);
@@ -150,7 +151,7 @@ void WebContentsZoomController::SetTemporaryZoomLevel(double level) {
// Notify observers of zoom level changes.
ZoomChangedEventData zoom_change_data(web_contents(), zoom_level_, level,
true /* temporary */, zoom_mode_);
for (WebContentsZoomObserver& observer : observers_)
for (auto& observer : observers_)
observer.OnZoomChanged(zoom_change_data);
}
@@ -264,8 +265,10 @@ void WebContentsZoomController::ResetZoomModeOnNavigationIfNeeded(
double old_zoom_level = zoom_map->GetZoomLevel(web_contents());
double new_zoom_level = zoom_map->GetZoomLevelForHostAndScheme(
url.scheme(), net::GetHostOrSpecFromURL(url));
event_data_ = std::make_unique<ZoomChangedEventData>(
web_contents(), old_zoom_level, new_zoom_level, false, ZOOM_MODE_DEFAULT);
// The call to ClearTemporaryZoomLevel() doesn't generate any events from
// HostZoomMap, but the call to UpdateState() at the end of
// DidFinishNavigation will notify our observers.
@@ -291,11 +294,12 @@ void WebContentsZoomController::DidFinishNavigation(
if (!navigation_handle->IsSameDocument()) {
ResetZoomModeOnNavigationIfNeeded(navigation_handle->GetURL());
SetZoomFactorOnNavigationIfNeeded(navigation_handle->GetURL());
// If the main frame's content has changed, the new page may have a
// different zoom level from the old one.
UpdateState(std::string());
}
// If the main frame's content has changed, the new page may have a different
// zoom level from the old one.
UpdateState(std::string());
DCHECK(!event_data_);
}

View File

@@ -7,6 +7,7 @@
#include <algorithm>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
@@ -69,7 +70,7 @@ struct Converter<network::mojom::CredentialsMode> {
network::mojom::CredentialsMode* out) {
using Val = network::mojom::CredentialsMode;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"include", Val::kInclude},
{"omit", Val::kOmit},
// Note: This only makes sense if the request
@@ -87,7 +88,7 @@ struct Converter<blink::mojom::FetchCacheMode> {
blink::mojom::FetchCacheMode* out) {
using Val = blink::mojom::FetchCacheMode;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"default", Val::kDefault},
{"force-cache", Val::kForceCache},
{"no-cache", Val::kValidateCache},
@@ -107,7 +108,7 @@ struct Converter<net::ReferrerPolicy> {
using Val = net::ReferrerPolicy;
// clang-format off
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"", Val::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN},
{"no-referrer", Val::NO_REFERRER},
{"no-referrer-when-downgrade", Val::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE},
@@ -181,6 +182,8 @@ class JSChunkedDataPipeGetter : public gin::Wrappable<JSChunkedDataPipeGetter>,
.SetMethod("done", &JSChunkedDataPipeGetter::Done);
}
const char* GetTypeName() override { return "JSChunkedDataPipeGetter"; }
static gin::WrapperInfo kWrapperInfo;
~JSChunkedDataPipeGetter() override = default;
@@ -547,7 +550,7 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
if (std::string mode; opts.Get("mode", &mode)) {
using Val = network::mojom::RequestMode;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"cors", Val::kCors},
{"navigate", Val::kNavigate},
{"no-cors", Val::kNoCors},
@@ -560,7 +563,7 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
if (std::string destination; opts.Get("destination", &destination)) {
using Val = network::mojom::RequestDestination;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"audio", Val::kAudio},
{"audioworklet", Val::kAudioWorklet},
{"document", Val::kDocument},
@@ -695,7 +698,7 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
return ret;
}
void SimpleURLLoaderWrapper::OnDataReceived(base::StringPiece string_piece,
void SimpleURLLoaderWrapper::OnDataReceived(std::string_view string_piece,
base::OnceClosure resume) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();

View File

@@ -5,6 +5,7 @@
#include "shell/common/asar/archive.h"
#include <string>
#include <string_view>
#include <utility>
#include <vector>
@@ -104,7 +105,7 @@ bool FillFileInfoWithNode(Archive::FileInfo* info,
const std::string* offset = node->FindString("offset");
if (offset &&
base::StringToUint64(base::StringPiece(*offset), &info->offset)) {
base::StringToUint64(std::string_view{*offset}, &info->offset)) {
info->offset += header_size;
} else {
return false;

View File

@@ -6,6 +6,7 @@
#include <algorithm>
#include <string>
#include <string_view>
#include <vector>
#include "base/containers/fixed_flat_map.h"
@@ -135,7 +136,7 @@ struct Converter<blink::WebMouseEvent::Button> {
blink::WebMouseEvent::Button* out) {
using Val = blink::WebMouseEvent::Button;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"left", Val::kLeft},
{"middle", Val::kMiddle},
{"right", Val::kRight},
@@ -148,7 +149,7 @@ struct Converter<blink::WebMouseEvent::Button> {
// these are the modifier names we both accept and return
static constexpr auto Modifiers =
base::MakeFixedFlatMapSorted<base::StringPiece, blink::WebInputEvent::Modifiers>({
base::MakeFixedFlatMapSorted<std::string_view, blink::WebInputEvent::Modifiers>({
{"alt", blink::WebInputEvent::Modifiers::kAltKey},
{"capslock", blink::WebInputEvent::Modifiers::kCapsLockOn},
{"control", blink::WebInputEvent::Modifiers::kControlKey},
@@ -167,14 +168,14 @@ static constexpr auto Modifiers =
// these are the modifier names we accept but do not return
static constexpr auto ModifierAliases =
base::MakeFixedFlatMapSorted<base::StringPiece, blink::WebInputEvent::Modifiers>({
base::MakeFixedFlatMapSorted<std::string_view, blink::WebInputEvent::Modifiers>({
{"cmd", blink::WebInputEvent::Modifiers::kMetaKey},
{"command", blink::WebInputEvent::Modifiers::kMetaKey},
{"ctrl", blink::WebInputEvent::Modifiers::kControlKey},
});
static constexpr auto ReferrerPolicies =
base::MakeFixedFlatMapSorted<base::StringPiece, network::mojom::ReferrerPolicy>({
base::MakeFixedFlatMapSorted<std::string_view, network::mojom::ReferrerPolicy>({
{"default", network::mojom::ReferrerPolicy::kDefault},
{"no-referrer", network::mojom::ReferrerPolicy::kNever},
{"no-referrer-when-downgrade", network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade},
@@ -197,8 +198,8 @@ struct Converter<blink::WebInputEvent::Modifiers> {
}
};
std::vector<base::StringPiece> ModifiersToArray(int modifiers) {
std::vector<base::StringPiece> modifier_strings;
std::vector<std::string_view> ModifiersToArray(int modifiers) {
std::vector<std::string_view> modifier_strings;
for (const auto& [name, mask] : Modifiers)
if (mask & modifiers)
@@ -463,7 +464,7 @@ v8::Local<v8::Value>
Converter<absl::optional<blink::mojom::FormControlType>>::ToV8(
v8::Isolate* isolate,
const absl::optional<blink::mojom::FormControlType>& in) {
base::StringPiece str{"none"};
std::string_view str{"none"};
if (in.has_value()) {
switch (*in) {
case blink::mojom::FormControlType::kButtonButton:

View File

@@ -5,6 +5,7 @@
#include "shell/common/gin_converters/content_converter.h"
#include <string>
#include <string_view>
#include "base/containers/fixed_flat_map.h"
#include "content/public/browser/context_menu_params.h"
@@ -24,7 +25,7 @@
namespace {
[[nodiscard]] constexpr base::StringPiece FormControlToInputFieldTypeString(
[[nodiscard]] constexpr std::string_view FormControlToInputFieldTypeString(
const absl::optional<blink::mojom::FormControlType> form_control_type) {
if (!form_control_type)
return "none";
@@ -323,7 +324,7 @@ bool Converter<content::StopFindAction>::FromV8(v8::Isolate* isolate,
content::StopFindAction* out) {
using Val = content::StopFindAction;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
base::MakeFixedFlatMapSorted<std::string_view, Val>({
{"activateSelection", Val::STOP_FIND_ACTION_ACTIVATE_SELECTION},
{"clearSelection", Val::STOP_FIND_ACTION_CLEAR_SELECTION},
{"keepSelection", Val::STOP_FIND_ACTION_KEEP_SELECTION},

Some files were not shown because too many files have changed in this diff Show More