]>
glassweightruler.freedombox.rocks Git - waydroid.git/blob - tools/helpers/lxc.py
1 # Copyright 2021 Erfan Abdi
2 # SPDX-License-Identifier: GPL-3.0-or-later
12 import tools
.helpers
.run
14 def get_lxc_version(args
):
15 if shutil
.which("lxc-info") is not None:
16 command
= ["lxc-info", "--version"]
17 version_str
= tools
.helpers
.run
.user(args
, command
, output_return
=True)
18 return int(version_str
[0])
22 def add_node_entry(nodes
, src
, dist
, mnt_type
, options
, check
):
23 if check
and not os
.path
.exists(src
):
25 entry
= "lxc.mount.entry = "
30 entry
+= mnt_type
+ " "
35 def generate_nodes_lxc_config(args
):
37 def make_entry(src
, dist
=None, mnt_type
="none", options
="bind,create=file,optional 0 0", check
=True):
38 return add_node_entry(nodes
, src
, dist
, mnt_type
, options
, check
)
41 make_entry("tmpfs", "dev", "tmpfs", "nosuid 0 0", False)
42 make_entry("/dev/zero")
43 make_entry("/dev/null")
44 make_entry("/dev/full")
45 make_entry("/dev/ashmem")
46 make_entry("/dev/fuse")
47 make_entry("/dev/ion")
48 make_entry("/dev/tty")
49 make_entry("/dev/char", options
="bind,create=dir,optional 0 0")
52 make_entry("/dev/kgsl-3d0")
53 make_entry("/dev/mali0")
54 make_entry("/dev/pvr_sync")
55 make_entry("/dev/pmsg0")
56 make_entry("/dev/dxg")
57 render
, _
= tools
.helpers
.gpu
.getDriNode(args
)
60 for n
in glob
.glob("/dev/fb*"):
62 for n
in glob
.glob("/dev/graphics/fb*"):
64 for n
in glob
.glob("/dev/video*"):
66 for n
in glob
.glob("/dev/dma_heap/*"):
70 make_entry("/dev/" + args
.BINDER_DRIVER
, "dev/binder", check
=False)
71 make_entry("/dev/" + args
.VNDBINDER_DRIVER
, "dev/vndbinder", check
=False)
72 make_entry("/dev/" + args
.HWBINDER_DRIVER
, "dev/hwbinder", check
=False)
74 if args
.vendor_type
!= "MAINLINE":
75 if not make_entry("/dev/hwbinder", "dev/host_hwbinder"):
76 raise OSError('Binder node "hwbinder" of host not found')
77 make_entry("/vendor", "vendor_extra", options
="rbind,optional 0 0")
79 # Necessary device nodes for adb
80 make_entry("none", "dev/pts", "devpts", "defaults,mode=644,ptmxmode=666,create=dir 0 0", False)
81 make_entry("/dev/uhid")
83 # TUN/TAP device node for VPN
84 make_entry("/dev/net/tun", "dev/tun")
86 # Low memory killer sys node
87 make_entry("/sys/module/lowmemorykiller", options
="bind,create=dir,optional 0 0")
89 # Mount host permissions
90 make_entry(tools
.config
.defaults
["host_perms"],
91 "vendor/etc/host-permissions", options
="bind,optional 0 0")
93 # Necessary sw_sync node for HWC
94 make_entry("/dev/sw_sync")
95 make_entry("/sys/kernel/debug", options
="rbind,create=dir,optional 0 0")
98 make_entry("/sys/class/leds/vibrator",
99 options
="bind,create=dir,optional 0 0")
100 make_entry("/sys/devices/virtual/timed_output/vibrator",
101 options
="bind,create=dir,optional 0 0")
103 # Media dev nodes (for Mediatek)
104 make_entry("/dev/Vcodec")
105 make_entry("/dev/MTK_SMI")
106 make_entry("/dev/mdp_sync")
107 make_entry("/dev/mtk_cmdq")
110 make_entry("tmpfs", "mnt_extra", "tmpfs", "nodev 0 0", False)
111 make_entry("/mnt/wslg", "mnt_extra/wslg",
112 options
="rbind,create=dir,optional 0 0")
114 # Make a tmpfs at every possible rootfs mountpoint
115 make_entry("tmpfs", "tmp", "tmpfs", "nodev 0 0", False)
116 make_entry("tmpfs", "var", "tmpfs", "nodev 0 0", False)
117 make_entry("tmpfs", "run", "tmpfs", "nodev 0 0", False)
120 make_entry("/system/etc/libnfc-nci.conf", options
="bind,optional 0 0")
124 LXC_APPARMOR_PROFILE
= "lxc-waydroid"
125 def get_apparmor_status(args
):
127 if shutil
.which("aa-enabled"):
128 enabled
= (tools
.helpers
.run
.user(args
, ["aa-enabled", "--quiet"], check
=False) == 0)
129 if not enabled
and shutil
.which("systemctl"):
130 enabled
= (tools
.helpers
.run
.user(args
, ["systemctl", "is-active", "-q", "apparmor"], check
=False) == 0)
132 with open("/sys/kernel/security/apparmor/profiles", "r") as f
:
133 enabled
&= (LXC_APPARMOR_PROFILE
in f
.read())
138 def set_lxc_config(args
):
139 lxc_path
= tools
.config
.defaults
["lxc"] + "/waydroid"
140 lxc_ver
= get_lxc_version(args
)
142 raise OSError("LXC is not installed")
143 config_paths
= tools
.config
.tools_src
+ "/data/configs/config_"
144 seccomp_profile
= tools
.config
.tools_src
+ "/data/configs/waydroid.seccomp"
146 config_snippets
= [ config_paths
+ "base" ]
147 # lxc v1 and v2 are bit special because some options got renamed later
149 config_snippets
.append(config_paths
+ "1")
151 for ver
in range(3, 5):
152 snippet
= config_paths
+ str(ver
)
153 if lxc_ver
>= ver
and os
.path
.exists(snippet
):
154 config_snippets
.append(snippet
)
156 command
= ["mkdir", "-p", lxc_path
]
157 tools
.helpers
.run
.user(args
, command
)
158 command
= ["sh", "-c", "cat {} > \"{}\"".format(' '.join('"{0}"'.format(w
) for w
in config_snippets
), lxc_path
+ "/config")]
159 tools
.helpers
.run
.user(args
, command
)
160 command
= ["sed", "-i", "s/LXCARCH/{}/".format(platform
.machine()), lxc_path
+ "/config"]
161 tools
.helpers
.run
.user(args
, command
)
162 command
= ["cp", "-fpr", seccomp_profile
, lxc_path
+ "/waydroid.seccomp"]
163 tools
.helpers
.run
.user(args
, command
)
164 if get_apparmor_status(args
):
165 command
= ["sed", "-i", "-E", "/lxc.aa_profile|lxc.apparmor.profile/ s/unconfined/{}/g".format(LXC_APPARMOR_PROFILE
), lxc_path
+ "/config"]
166 tools
.helpers
.run
.user(args
, command
)
168 nodes
= generate_nodes_lxc_config(args
)
169 config_nodes_tmp_path
= args
.work
+ "/config_nodes"
170 config_nodes
= open(config_nodes_tmp_path
, "w")
172 config_nodes
.write(node
+ "\n")
174 command
= ["mv", config_nodes_tmp_path
, lxc_path
]
175 tools
.helpers
.run
.user(args
, command
)
178 open(os
.path
.join(lxc_path
, "config_session"), mode
="w").close()
180 def generate_session_lxc_config(args
, session
):
182 def make_entry(src
, dist
=None, mnt_type
="none", options
="rbind,create=file 0 0"):
183 if any(x
in src
for x
in ["\n", "\r"]):
184 logging
.warning("User-provided mount path contains illegal character: " + src
)
186 if dist
is None and (not os
.path
.exists(src
) or
187 str(os
.stat(src
).st_uid
) != session
["user_id"]):
188 logging
.warning("User-provided mount path is not owned by user: " + src
)
190 return add_node_entry(nodes
, src
, dist
, mnt_type
, options
, check
=False)
192 # Make sure XDG_RUNTIME_DIR exists
193 if not make_entry("tmpfs", tools
.config
.defaults
["container_xdg_runtime_dir"], options
="create=dir 0 0"):
194 raise OSError("Failed to create XDG_RUNTIME_DIR mount point")
196 wayland_host_socket
= os
.path
.realpath(os
.path
.join(session
["xdg_runtime_dir"], session
["wayland_display"]))
197 wayland_container_socket
= os
.path
.realpath(os
.path
.join(tools
.config
.defaults
["container_xdg_runtime_dir"], tools
.config
.defaults
["container_wayland_display"]))
198 if not make_entry(wayland_host_socket
, wayland_container_socket
[1:]):
199 raise OSError("Failed to bind Wayland socket")
201 # Make sure PULSE_RUNTIME_DIR exists
202 pulse_host_socket
= os
.path
.join(session
["pulse_runtime_path"], "native")
203 pulse_container_socket
= os
.path
.join(tools
.config
.defaults
["container_pulse_runtime_path"], "native")
204 make_entry(pulse_host_socket
, pulse_container_socket
[1:])
206 if not make_entry(session
["waydroid_data"], "data", options
="rbind 0 0"):
207 raise OSError("Failed to bind userdata")
209 lxc_path
= tools
.config
.defaults
["lxc"] + "/waydroid"
210 config_nodes_tmp_path
= args
.work
+ "/config_session"
211 config_nodes
= open(config_nodes_tmp_path
, "w")
213 config_nodes
.write(node
+ "\n")
215 command
= ["mv", config_nodes_tmp_path
, lxc_path
]
216 tools
.helpers
.run
.user(args
, command
)
218 def make_base_props(args
):
219 def find_hal(hardware
):
221 "ro.hardware." + hardware
,
226 for p
in hardware_props
:
227 prop
= tools
.helpers
.props
.host_get(args
, p
)
229 for lib
in ["/odm/lib", "/odm/lib64", "/vendor/lib", "/vendor/lib64", "/system/lib", "/system/lib64"]:
230 hal_file
= lib
+ "/hw/" + hardware
+ "." + prop
+ ".so"
231 if os
.path
.isfile(hal_file
):
236 if args
.vendor_type
== "MAINLINE":
240 sm
= gbinder
.ServiceManager("/dev/hwbinder")
241 return intf
in sm
.list_sync()
247 if not os
.path
.exists("/dev/ashmem"):
248 props
.append("sys.use_memfd=true")
250 egl
= tools
.helpers
.props
.host_get(args
, "ro.hardware.egl")
251 dri
, _
= tools
.helpers
.gpu
.getDriNode(args
)
253 gralloc
= find_hal("gralloc")
255 if find_hidl("android.hardware.graphics.allocator@4.0::IAllocator/default"):
261 props
.append("gralloc.gbm.device=" + dri
)
265 props
.append("debug.stagefright.ccodec=0")
266 props
.append("ro.hardware.gralloc=" + gralloc
)
269 props
.append("ro.hardware.egl=" + egl
)
271 media_profiles
= tools
.helpers
.props
.host_get(args
, "media.settings.xml")
272 if media_profiles
!= "":
273 media_profiles
= media_profiles
.replace("vendor/", "vendor_extra/")
274 media_profiles
= media_profiles
.replace("odm/", "odm_extra/")
275 props
.append("media.settings.xml=" + media_profiles
)
277 ccodec
= tools
.helpers
.props
.host_get(args
, "debug.stagefright.ccodec")
279 props
.append("debug.stagefright.ccodec=" + ccodec
)
281 ext_library
= tools
.helpers
.props
.host_get(args
, "ro.vendor.extension_library")
282 if ext_library
!= "":
283 ext_library
= ext_library
.replace("vendor/", "vendor_extra/")
284 ext_library
= ext_library
.replace("odm/", "odm_extra/")
285 props
.append("ro.vendor.extension_library=" + ext_library
)
287 vulkan
= find_hal("vulkan")
288 if not vulkan
and dri
:
289 vulkan
= tools
.helpers
.gpu
.getVulkanDriver(args
, os
.path
.basename(dri
))
291 props
.append("ro.hardware.vulkan=" + vulkan
)
293 treble
= tools
.helpers
.props
.host_get(args
, "ro.treble.enabled")
295 camera
= find_hal("camera")
297 props
.append("ro.hardware.camera=" + camera
)
299 if args
.vendor_type
== "MAINLINE":
300 props
.append("ro.hardware.camera=v4l2")
302 opengles
= tools
.helpers
.props
.host_get(args
, "ro.opengles.version")
305 props
.append("ro.opengles.version=" + opengles
)
307 if args
.images_path
not in tools
.config
.defaults
["preinstalled_images_paths"]:
308 props
.append("waydroid.system_ota=" + args
.system_ota
)
309 props
.append("waydroid.vendor_ota=" + args
.vendor_ota
)
311 props
.append("waydroid.updater.disabled=true")
313 props
.append("waydroid.tools_version=" + tools
.config
.version
)
315 if args
.vendor_type
== "MAINLINE":
316 props
.append("ro.vndk.lite=true")
318 for product
in ["brand", "device", "manufacturer", "model", "name"]:
319 prop_product
= tools
.helpers
.props
.host_get(
320 args
, "ro.product.vendor." + product
)
321 if prop_product
!= "":
322 props
.append("ro.product.waydroid." + product
+ "=" + prop_product
)
324 if os
.path
.isfile("/proc/device-tree/" + product
):
325 with open("/proc/device-tree/" + product
) as f
:
326 f_value
= f
.read().strip().rstrip('\x00')
328 props
.append("ro.product.waydroid." +
329 product
+ "=" + f_value
)
331 prop_fp
= tools
.helpers
.props
.host_get(args
, "ro.vendor.build.fingerprint")
333 props
.append("ro.build.fingerprint=" + prop_fp
)
335 # now append/override with values in [properties] section of waydroid.cfg
336 cfg
= tools
.config
.load(args
)
337 for k
, v
in cfg
["properties"].items():
338 for idx
, elem
in enumerate(props
):
341 props
.append(k
+"="+v
)
343 base_props
= open(args
.work
+ "/waydroid_base.prop", "w")
345 base_props
.write(prop
+ "\n")
349 def setup_host_perms(args
):
350 if not os
.path
.exists(tools
.config
.defaults
["host_perms"]):
351 os
.mkdir(tools
.config
.defaults
["host_perms"])
353 treble
= tools
.helpers
.props
.host_get(args
, "ro.treble.enabled")
357 sku
= tools
.helpers
.props
.host_get(args
, "ro.boot.product.hardware.sku")
360 glob
.glob("/vendor/etc/permissions/android.hardware.nfc.*"))
361 if os
.path
.exists("/vendor/etc/permissions/android.hardware.consumerir.xml"):
362 copy_list
.append("/vendor/etc/permissions/android.hardware.consumerir.xml")
364 glob
.glob("/odm/etc/permissions/android.hardware.nfc.*"))
365 if os
.path
.exists("/odm/etc/permissions/android.hardware.consumerir.xml"):
366 copy_list
.append("/odm/etc/permissions/android.hardware.consumerir.xml")
369 glob
.glob("/odm/etc/permissions/sku_{}/android.hardware.nfc.*".format(sku
)))
370 if os
.path
.exists("/odm/etc/permissions/sku_{}/android.hardware.consumerir.xml".format(sku
)):
372 "/odm/etc/permissions/sku_{}/android.hardware.consumerir.xml".format(sku
))
374 for filename
in copy_list
:
375 shutil
.copy(filename
, tools
.config
.defaults
["host_perms"])
378 command
= ["lxc-info", "-P", tools
.config
.defaults
["lxc"], "-n", "waydroid", "-sH"]
380 return tools
.helpers
.run
.user(args
, command
, output_return
=True).strip()
382 logging
.info("Couldn't get LXC status. Assuming STOPPED.")
385 def wait_for_running(args
):
386 lxc_status
= status(args
)
388 while lxc_status
!= "RUNNING" and timeout
> 0:
389 lxc_status
= status(args
)
391 "waiting {} seconds for container to start...".format(timeout
))
392 timeout
= timeout
- 1
394 if lxc_status
!= "RUNNING":
395 raise OSError("container failed to start")
398 command
= ["lxc-start", "-P", tools
.config
.defaults
["lxc"],
399 "-F", "-n", "waydroid", "--", "/init"]
400 tools
.helpers
.run
.user(args
, command
, output
="background")
401 wait_for_running(args
)
402 # Workaround lxc-start changing stdout/stderr permissions to 700
403 os
.chmod(args
.log
, 0o666)
406 command
= ["lxc-stop", "-P",
407 tools
.config
.defaults
["lxc"], "-n", "waydroid", "-k"]
408 tools
.helpers
.run
.user(args
, command
)
411 command
= ["lxc-freeze", "-P", tools
.config
.defaults
["lxc"], "-n", "waydroid"]
412 tools
.helpers
.run
.user(args
, command
)
415 command
= ["lxc-unfreeze", "-P",
416 tools
.config
.defaults
["lxc"], "-n", "waydroid"]
417 tools
.helpers
.run
.user(args
, command
)
420 "PATH": "/product/bin:/apex/com.android.runtime/bin:/apex/com.android.art/bin:/system_ext/bin:/system/bin:/system/xbin:/odm/bin:/vendor/bin:/vendor/xbin",
421 "ANDROID_ROOT": "/system",
422 "ANDROID_DATA": "/data",
423 "ANDROID_STORAGE": "/storage",
424 "ANDROID_ART_ROOT": "/apex/com.android.art",
425 "ANDROID_I18N_ROOT": "/apex/com.android.i18n",
426 "ANDROID_TZDATA_ROOT": "/apex/com.android.tzdata",
427 "ANDROID_RUNTIME_ROOT": "/apex/com.android.runtime",
428 "BOOTCLASSPATH": "/apex/com.android.art/javalib/core-oj.jar:/apex/com.android.art/javalib/core-libart.jar:/apex/com.android.art/javalib/core-icu4j.jar:/apex/com.android.art/javalib/okhttp.jar:/apex/com.android.art/javalib/bouncycastle.jar:/apex/com.android.art/javalib/apache-xml.jar:/system/framework/framework.jar:/system/framework/ext.jar:/system/framework/telephony-common.jar:/system/framework/voip-common.jar:/system/framework/ims-common.jar:/system/framework/framework-atb-backward-compatibility.jar:/apex/com.android.conscrypt/javalib/conscrypt.jar:/apex/com.android.media/javalib/updatable-media.jar:/apex/com.android.mediaprovider/javalib/framework-mediaprovider.jar:/apex/com.android.os.statsd/javalib/framework-statsd.jar:/apex/com.android.permission/javalib/framework-permission.jar:/apex/com.android.sdkext/javalib/framework-sdkextensions.jar:/apex/com.android.wifi/javalib/framework-wifi.jar:/apex/com.android.tethering/javalib/framework-tethering.jar"
431 def android_env_attach_options(args
):
432 local_env
= ANDROID_ENV
.copy()
433 # Include CLASSPATH env that was generated by Android
434 command
= ["lxc-attach", "-P", tools
.config
.defaults
["lxc"],
435 "-n", "waydroid", "--clear-env", "--",
436 "/system/bin/cat" ,"/data/system/environ/classpath"]
437 classpath
= tools
.helpers
.run
.user(args
, command
, output_return
=True).strip()
438 for line
in classpath
.splitlines():
439 _
, k
, v
= line
.split(' ', 2)
441 env
= [k
+ "=" + v
for k
, v
in local_env
.items()]
442 return [x
for var
in env
for x
in ("--set-var", var
)]
446 if state
== "FROZEN":
448 elif state
!= "RUNNING":
449 logging
.error("WayDroid container is {}".format(state
))
451 command
= ["lxc-attach", "-P", tools
.config
.defaults
["lxc"],
452 "-n", "waydroid", "--clear-env"]
453 command
.extend(android_env_attach_options(args
))
455 command
.append("--uid="+str(args
.uid
))
457 command
.append("--gid="+str(args
.gid
))
459 command
.append("--gid="+str(args
.uid
))
460 if args
.nolsm
or args
.allcaps
or args
.nocgroup
:
461 elevatedprivs
= "--elevated-privileges="
476 elevatedprivs
+="CGROUP"
478 command
.append(elevatedprivs
)
479 if args
.context
!=None and not args
.nolsm
:
480 command
.append("--context="+args
.context
)
483 command
.extend(args
.COMMAND
)
485 command
.append("/system/bin/sh")
488 subprocess
.run(command
)
489 except KeyboardInterrupt:
492 if state
== "FROZEN":
496 args
.COMMAND
= ["/system/bin/logcat"]