0
# Platform Support
1
2
PyArmor provides comprehensive cross-platform obfuscation with support for 40+ target platforms including Windows, Linux, macOS, FreeBSD, and Android. The platform system handles automatic detection, library management, and cross-compilation for diverse deployment environments.
3
4
## Capabilities
5
6
### Platform Detection and Information
7
8
#### Hardware Information Functions
9
10
Display and query hardware information for device binding and platform identification.
11
12
```python { .api }
13
def show_hd_info(name: str = None) -> str:
14
"""
15
Display hardware information for binding and platform identification.
16
17
Args:
18
name (str, optional): Specific hardware component to query
19
- 'disk': Hard disk serial numbers
20
- 'mac': Network MAC addresses
21
- 'ipv4': IPv4 network addresses
22
- 'domain': Domain name information
23
- 'cpu': CPU identification
24
- None: All available hardware information
25
26
Returns:
27
str: Formatted hardware information string
28
29
Example output:
30
Hardware information:
31
Disk serial number: ABCD1234567890EFGH
32
MAC address: 00:11:22:33:44:55, AA:BB:CC:DD:EE:FF
33
IPv4 address: 192.168.1.100, 10.0.0.50
34
Domain name: workstation.company.com
35
CPU info: Intel64 Family 6 Model 142 Stepping 10
36
"""
37
38
def get_platform_name() -> str:
39
"""
40
Get current system platform specification.
41
42
Returns:
43
str: Platform specification in format 'os.architecture'
44
45
Examples:
46
'linux.x86_64' # Linux 64-bit Intel/AMD
47
'windows.x86_64' # Windows 64-bit Intel/AMD
48
'darwin.x86_64' # macOS Intel
49
'darwin.arm64' # macOS Apple Silicon
50
'linux.aarch64' # Linux ARM64
51
"""
52
53
def format_platform(system: str = None, machine: str = None) -> str:
54
"""
55
Format platform specification from system and machine info.
56
57
Args:
58
system (str, optional): Operating system name (auto-detected if None)
59
machine (str, optional): Machine architecture (auto-detected if None)
60
61
Returns:
62
str: Formatted platform specification
63
64
System mappings:
65
'Linux' -> 'linux'
66
'Windows' -> 'windows'
67
'Darwin' -> 'darwin'
68
'FreeBSD' -> 'freebsd'
69
'CYGWIN_NT-*' -> 'cygwin'
70
71
Architecture mappings:
72
'x86_64', 'AMD64' -> 'x86_64'
73
'i386', 'i686' -> 'x86'
74
'aarch64', 'arm64' -> 'aarch64' or 'arm64' (macOS)
75
'armv7l' -> 'armv7'
76
"""
77
```
78
79
### Platform Library Management
80
81
#### Library Download and Management
82
83
Download and manage platform-specific runtime libraries for cross-platform obfuscation.
84
85
```python { .api }
86
def download_pytransform(platname: str, **kwargs) -> None:
87
"""
88
Download platform-specific PyTransform runtime library.
89
90
Args:
91
platname (str): Target platform specification
92
**kwargs: Download options
93
- update (bool): Force update existing library (default: False)
94
- timeout (float): Download timeout in seconds (default: 6.0)
95
- url (str): Custom download URL base
96
- output (str): Custom output directory
97
98
Raises:
99
DownloadError: If download fails or times out
100
PlatformError: If platform is not supported
101
NetworkError: If network connection fails
102
103
Example platforms:
104
'linux.x86_64', 'windows.x86_64', 'darwin.x86_64',
105
'linux.aarch64', 'android.aarch64', 'freebsd.x86_64'
106
"""
107
108
def check_cross_platform(platforms: list, **kwargs) -> None:
109
"""
110
Validate cross-platform obfuscation configuration and requirements.
111
112
Args:
113
platforms (list): List of target platform specifications
114
**kwargs: Validation options
115
- enable_bcc (bool): Check BCC mode compatibility
116
- enable_themida (bool): Check Themida compatibility
117
- download (bool): Auto-download missing libraries
118
119
Raises:
120
PlatformError: If platform combination is invalid
121
CompatibilityError: If features are incompatible with platforms
122
LibraryError: If required libraries are missing
123
124
Validation checks:
125
- Platform availability and support status
126
- Feature compatibility (BCC, Themida, etc.)
127
- Required library availability
128
- Cross-platform restriction conflicts
129
"""
130
131
def list_available_platforms() -> list:
132
"""
133
Get list of all supported platform specifications.
134
135
Returns:
136
list: All supported platform specifications
137
138
Categories:
139
- Windows: windows.x86_64, windows.x86
140
- Linux: linux.x86_64, linux.x86, linux.aarch64, linux.armv7
141
- macOS: darwin.x86_64, darwin.arm64
142
- FreeBSD: freebsd.x86_64
143
- Android: android.x86_64, android.x86, android.aarch64, android.armv7
144
- Alpine: alpine.x86_64, alpine.aarch64
145
- Specialized: linux.mips32el, linux.mips64el, linux.ppc64le, linux.riscv64
146
"""
147
148
def get_library_path(platname: str) -> str:
149
"""
150
Get local path to platform-specific runtime library.
151
152
Args:
153
platname (str): Platform specification
154
155
Returns:
156
str: Path to runtime library file
157
158
Raises:
159
LibraryError: If library not found or not downloaded
160
"""
161
```
162
163
### Cross-Platform Obfuscation
164
165
#### Multi-Platform Generation
166
167
Generate obfuscated scripts compatible with multiple target platforms.
168
169
```python { .api }
170
def generate_cross_platform_runtime(capsule, output: str, platforms: list, **kwargs) -> None:
171
"""
172
Generate runtime package supporting multiple platforms.
173
174
Args:
175
capsule: Protection capsule
176
output (str): Output directory
177
platforms (list): Target platform specifications
178
**kwargs: Runtime options
179
- shared (bool): Generate shared runtime package
180
- suffix (str): Runtime file suffix
181
- bootstrap (int): Bootstrap generation mode
182
183
Generated structure:
184
runtime/
185
├── __init__.py
186
├── linux/
187
│ └── x86_64/
188
│ └── _pytransform.so
189
├── windows/
190
│ └── x86_64/
191
│ └── _pytransform.dll
192
└── darwin/
193
└── x86_64/
194
└── _pytransform.dylib
195
"""
196
197
def obfuscate_for_platforms(scripts: list, platforms: list, **kwargs) -> dict:
198
"""
199
Obfuscate scripts for multiple target platforms.
200
201
Args:
202
scripts (list): List of script file paths
203
platforms (list): Target platform specifications
204
**kwargs: Obfuscation options
205
- output (str): Base output directory
206
- shared_runtime (bool): Use shared runtime package
207
- platform_suffix (bool): Add platform suffix to output
208
209
Returns:
210
dict: Mapping of platforms to output directories
211
212
Example output structure:
213
dist/
214
├── linux.x86_64/
215
│ ├── main.py
216
│ └── pyarmor_runtime/
217
├── windows.x86_64/
218
│ ├── main.py
219
│ └── pyarmor_runtime/
220
└── shared_runtime/ # If shared_runtime=True
221
└── pyarmor_runtime/
222
"""
223
```
224
225
### Platform-Specific Features
226
227
#### Platform Capability Detection
228
229
```python { .api }
230
def get_platform_features(platname: str) -> dict:
231
"""
232
Get available features for specific platform.
233
234
Args:
235
platname (str): Platform specification
236
237
Returns:
238
dict: Available features and capabilities
239
- bcc_supported (bool): BCC mode support
240
- jit_supported (bool): JIT compilation support
241
- rft_supported (bool): RFT transformation support
242
- themida_supported (bool): Themida protection support
243
- vm_supported (bool): VM mode support
244
- architectures (list): Supported architectures
245
- max_protection_level (int): Maximum protection level
246
247
Example return:
248
{
249
'bcc_supported': True,
250
'jit_supported': True,
251
'rft_supported': True,
252
'themida_supported': False, # Windows only
253
'vm_supported': True,
254
'architectures': ['x86_64'],
255
'max_protection_level': 5
256
}
257
"""
258
259
def check_platform_compatibility(platname: str, features: list) -> dict:
260
"""
261
Check feature compatibility for specific platform.
262
263
Args:
264
platname (str): Platform specification
265
features (list): Features to check compatibility
266
267
Returns:
268
dict: Compatibility results
269
- compatible (bool): Overall compatibility
270
- supported_features (list): Supported features
271
- unsupported_features (list): Unsupported features
272
- warnings (list): Compatibility warnings
273
"""
274
```
275
276
### Embedded and Specialized Platforms
277
278
#### Embedded System Support
279
280
```python { .api }
281
def configure_embedded_platform(platname: str, **kwargs) -> dict:
282
"""
283
Configure obfuscation for embedded systems and IoT devices.
284
285
Args:
286
platname (str): Embedded platform specification
287
**kwargs: Embedded-specific options
288
- memory_limit (int): Memory usage limit in MB
289
- minimal_runtime (bool): Use minimal runtime package
290
- startup_optimization (bool): Optimize for fast startup
291
- size_optimization (bool): Optimize for small size
292
293
Returns:
294
dict: Optimized configuration for embedded platform
295
296
Supported embedded platforms:
297
- linux.armv7 (Raspberry Pi, BeagleBone)
298
- linux.aarch64 (Raspberry Pi 4, Jetson Nano)
299
- linux.mips32el (OpenWrt routers)
300
- android.armv7 (ARM Android devices)
301
- android.aarch64 (ARM64 Android devices)
302
"""
303
304
def optimize_for_container(platname: str, container_type: str) -> dict:
305
"""
306
Optimize obfuscation for containerized deployment.
307
308
Args:
309
platname (str): Container platform specification
310
container_type (str): Container type ('docker', 'podman', 'alpine')
311
312
Returns:
313
dict: Container-optimized configuration
314
315
Optimizations:
316
- Minimal runtime dependencies
317
- Static linking where possible
318
- Reduced file system footprint
319
- Container-friendly licensing
320
"""
321
```
322
323
### Platform Constants and Mappings
324
325
```python { .api }
326
# Supported platforms by category
327
WINDOWS_PLATFORMS = [
328
'windows.x86_64', # Windows 64-bit
329
'windows.x86', # Windows 32-bit
330
'cygwin.x86_64' # Cygwin environment
331
]
332
333
LINUX_PLATFORMS = [
334
'linux.x86_64', # Linux Intel/AMD 64-bit
335
'linux.x86', # Linux Intel/AMD 32-bit
336
'linux.aarch64', # Linux ARM 64-bit
337
'linux.armv7', # Linux ARM 32-bit
338
'linux.mips32el', # Linux MIPS 32-bit little-endian
339
'linux.mips64el', # Linux MIPS 64-bit little-endian
340
'linux.ppc64le', # Linux PowerPC 64-bit little-endian
341
'linux.riscv64' # Linux RISC-V 64-bit
342
]
343
344
DARWIN_PLATFORMS = [
345
'darwin.x86_64', # macOS Intel
346
'darwin.arm64' # macOS Apple Silicon
347
]
348
349
FREEBSD_PLATFORMS = [
350
'freebsd.x86_64' # FreeBSD 64-bit
351
]
352
353
ANDROID_PLATFORMS = [
354
'android.x86_64', # Android Intel/AMD 64-bit
355
'android.x86', # Android Intel/AMD 32-bit
356
'android.aarch64', # Android ARM 64-bit
357
'android.armv7' # Android ARM 32-bit
358
]
359
360
ALPINE_PLATFORMS = [
361
'alpine.x86_64', # Alpine Linux 64-bit
362
'alpine.aarch64', # Alpine Linux ARM 64-bit
363
'alpine.mips32el', # Alpine Linux MIPS 32-bit
364
'alpine.mips64el', # Alpine Linux MIPS 64-bit
365
'alpine.ppc64le', # Alpine Linux PowerPC 64-bit
366
'alpine.riscv64' # Alpine Linux RISC-V 64-bit
367
]
368
369
# Platform feature matrix
370
PLATFORM_FEATURES = {
371
'windows.x86_64': {
372
'bcc': True, 'jit': True, 'rft': True, 'themida': True, 'vm': True
373
},
374
'linux.x86_64': {
375
'bcc': True, 'jit': True, 'rft': True, 'themida': False, 'vm': True
376
},
377
'darwin.x86_64': {
378
'bcc': True, 'jit': True, 'rft': True, 'themida': False, 'vm': True
379
},
380
'darwin.arm64': {
381
'bcc': True, 'jit': True, 'rft': True, 'themida': False, 'vm': True
382
},
383
'linux.aarch64': {
384
'bcc': True, 'jit': False, 'rft': True, 'themida': False, 'vm': True
385
}
386
}
387
```
388
389
## Usage Examples
390
391
### Platform Information
392
393
```python
394
from pyarmor import utils
395
396
# Show all hardware information
397
print(utils.show_hd_info())
398
399
# Show specific hardware info
400
print("MAC addresses:", utils.show_hd_info('mac'))
401
print("Disk serials:", utils.show_hd_info('disk'))
402
print("IP addresses:", utils.show_hd_info('ipv4'))
403
404
# Get current platform
405
current_platform = utils.get_platform_name()
406
print(f"Current platform: {current_platform}")
407
408
# Format custom platform
409
custom_platform = utils.format_platform('Linux', 'aarch64')
410
print(f"Custom platform: {custom_platform}")
411
```
412
413
### Cross-Platform Library Management
414
415
```python
416
# List all supported platforms
417
platforms = utils.list_available_platforms()
418
print("Supported platforms:")
419
for platform in platforms:
420
print(f" {platform}")
421
422
# Download libraries for target platforms
423
target_platforms = ['linux.x86_64', 'windows.x86_64', 'darwin.x86_64']
424
425
for platform in target_platforms:
426
try:
427
print(f"Downloading library for {platform}")
428
utils.download_pytransform(platform, update=True, timeout=30.0)
429
print(f" Success")
430
except Exception as e:
431
print(f" Failed: {e}")
432
433
# Validate cross-platform setup
434
try:
435
utils.check_cross_platform(target_platforms, download=True)
436
print("Cross-platform setup validated")
437
except Exception as e:
438
print(f"Validation failed: {e}")
439
```
440
441
### Multi-Platform Obfuscation
442
443
```python
444
from pyarmor import utils
445
446
# Initialize PyArmor
447
utils.pytransform_bootstrap()
448
449
# Target platforms for deployment
450
platforms = [
451
'linux.x86_64', # Linux servers
452
'windows.x86_64', # Windows desktops
453
'darwin.x86_64', # macOS Intel
454
'darwin.arm64', # macOS Apple Silicon
455
'linux.aarch64' # ARM servers (Raspberry Pi, AWS Graviton)
456
]
457
458
# Generate capsule
459
capsule = utils.make_capsule()
460
461
# Generate cross-platform runtime
462
utils.generate_cross_platform_runtime(
463
capsule,
464
"dist/runtime",
465
platforms,
466
shared=True,
467
bootstrap=1
468
)
469
470
# Obfuscate scripts for all platforms
471
scripts = ['main.py', 'module1.py', 'module2.py']
472
473
for platform in platforms:
474
output_dir = f"dist/{platform}"
475
print(f"Obfuscating for {platform}")
476
477
# Platform-specific obfuscation
478
for script in scripts:
479
utils.encrypt_script(
480
capsule,
481
script,
482
f"{output_dir}/{script}",
483
platform=platform,
484
obf_code=2,
485
mix_str=1
486
)
487
488
# Copy runtime for platform
489
utils.make_runtime(capsule, output_dir, platform=platform)
490
```
491
492
### Platform-Specific Optimization
493
494
```python
495
# Configure for embedded Linux ARM
496
embedded_config = utils.configure_embedded_platform(
497
'linux.armv7',
498
memory_limit=128, # 128MB memory limit
499
minimal_runtime=True, # Minimal runtime package
500
startup_optimization=True, # Fast startup
501
size_optimization=True # Small binary size
502
)
503
504
# Apply embedded configuration
505
utils.encrypt_script(
506
capsule,
507
'embedded_app.py',
508
'dist/embedded/embedded_app.py',
509
**embedded_config
510
)
511
512
# Container optimization for Docker
513
container_config = utils.optimize_for_container(
514
'alpine.x86_64',
515
'docker'
516
)
517
518
# Apply container configuration
519
utils.encrypt_script(
520
capsule,
521
'container_app.py',
522
'dist/container/container_app.py',
523
**container_config
524
)
525
```
526
527
### Feature Compatibility Checking
528
529
```python
530
# Check platform capabilities
531
def check_platform_setup(platforms, required_features):
532
"""Check if platforms support required features."""
533
534
for platform in platforms:
535
print(f"\nChecking {platform}:")
536
537
# Get platform features
538
features = utils.get_platform_features(platform)
539
print(f" Available features: {features}")
540
541
# Check compatibility
542
compat = utils.check_platform_compatibility(platform, required_features)
543
544
if compat['compatible']:
545
print(f" ✓ Compatible")
546
else:
547
print(f" ✗ Incompatible")
548
print(f" Unsupported: {compat['unsupported_features']}")
549
550
if compat['warnings']:
551
print(f" Warnings: {compat['warnings']}")
552
553
# Check setup for advanced features
554
required_features = ['bcc', 'jit', 'rft']
555
target_platforms = ['linux.x86_64', 'windows.x86_64', 'linux.aarch64']
556
557
check_platform_setup(target_platforms, required_features)
558
```
559
560
### Advanced Cross-Platform Deployment
561
562
```python
563
# Enterprise multi-platform deployment
564
def deploy_cross_platform(app_files, target_environments):
565
"""Deploy application across multiple environments."""
566
567
capsule = utils.make_capsule()
568
deployment_map = {}
569
570
for env_name, env_config in target_environments.items():
571
platforms = env_config['platforms']
572
features = env_config.get('features', {})
573
574
print(f"Preparing {env_name} deployment...")
575
576
# Validate platform compatibility
577
utils.check_cross_platform(platforms, **features)
578
579
# Create environment-specific output
580
env_output = f"dist/{env_name}"
581
582
# Configure obfuscation for environment
583
obf_options = {
584
'obf_code': env_config.get('protection_level', 2),
585
'mix_str': env_config.get('string_protection', True),
586
'restrict': env_config.get('restrict_mode', 2),
587
**features
588
}
589
590
# Generate runtime for all platforms in environment
591
utils.generate_cross_platform_runtime(
592
capsule,
593
f"{env_output}/runtime",
594
platforms,
595
shared=True
596
)
597
598
# Obfuscate application files
599
for app_file in app_files:
600
utils.encrypt_script(
601
capsule,
602
app_file,
603
f"{env_output}/{app_file}",
604
platform=",".join(platforms),
605
**obf_options
606
)
607
608
deployment_map[env_name] = {
609
'output': env_output,
610
'platforms': platforms,
611
'files': app_files
612
}
613
614
return deployment_map
615
616
# Define deployment environments
617
environments = {
618
'production': {
619
'platforms': ['linux.x86_64', 'windows.x86_64'],
620
'protection_level': 5, # Maximum protection
621
'string_protection': True,
622
'restrict_mode': 3,
623
'features': {'enable_bcc': True, 'enable_rft': True}
624
},
625
'staging': {
626
'platforms': ['linux.x86_64'],
627
'protection_level': 2, # Moderate protection
628
'features': {'enable_jit': True}
629
},
630
'embedded': {
631
'platforms': ['linux.armv7', 'linux.aarch64'],
632
'protection_level': 1, # Basic protection for performance
633
'memory_limit': 256,
634
'minimal_runtime': True
635
}
636
}
637
638
# Deploy application
639
app_files = ['main.py', 'core.py', 'utils.py']
640
deployment = deploy_cross_platform(app_files, environments)
641
642
print("Deployment complete:")
643
for env, info in deployment.items():
644
print(f" {env}: {info['output']} ({len(info['platforms'])} platforms)")
645
```
646
647
## Error Handling
648
649
```python
650
from pyarmor.utils import DownloadError, PlatformError, LibraryError
651
652
try:
653
# Platform operations
654
utils.download_pytransform('linux.x86_64')
655
utils.check_cross_platform(['invalid.platform'])
656
657
except DownloadError as e:
658
print(f"Download failed: {e}")
659
print("Check network connection and try again")
660
661
except PlatformError as e:
662
print(f"Platform error: {e}")
663
print("Check platform specification format")
664
665
except LibraryError as e:
666
print(f"Library error: {e}")
667
print("Try downloading platform libraries manually")
668
669
# Safe platform operations
670
def safe_download_platform(platform, retries=3):
671
"""Safely download platform library with retries."""
672
for attempt in range(retries):
673
try:
674
utils.download_pytransform(platform, timeout=30.0)
675
return True
676
except Exception as e:
677
print(f"Attempt {attempt + 1} failed: {e}")
678
if attempt == retries - 1:
679
return False
680
return False
681
682
# Example usage
683
if safe_download_platform('linux.x86_64'):
684
print("Platform library downloaded successfully")
685
else:
686
print("Failed to download platform library after all retries")
687
```