forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzipimport.c
1664 lines (1443 loc) · 48.7 KB
/
zipimport.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Python.h"
#include "internal/pystate.h"
#include "structmember.h"
#include "osdefs.h"
#include "marshal.h"
#include <time.h>
#define IS_SOURCE 0x0
#define IS_BYTECODE 0x1
#define IS_PACKAGE 0x2
struct st_zip_searchorder {
char suffix[14];
int type;
};
#ifdef ALTSEP
_Py_IDENTIFIER(replace);
#endif
/* zip_searchorder defines how we search for a module in the Zip
archive: we first search for a package __init__, then for
non-package .pyc, and .py entries. The .pyc entries
are swapped by initzipimport() if we run in optimized mode. Also,
'/' is replaced by SEP there. */
static struct st_zip_searchorder zip_searchorder[] = {
{"/__init__.pyc", IS_PACKAGE | IS_BYTECODE},
{"/__init__.py", IS_PACKAGE | IS_SOURCE},
{".pyc", IS_BYTECODE},
{".py", IS_SOURCE},
{"", 0}
};
/* zipimporter object definition and support */
typedef struct _zipimporter ZipImporter;
struct _zipimporter {
PyObject_HEAD
PyObject *archive; /* pathname of the Zip archive,
decoded from the filesystem encoding */
PyObject *prefix; /* file prefix: "a/sub/directory/",
encoded to the filesystem encoding */
PyObject *files; /* dict with file info {path: toc_entry} */
};
static PyObject *ZipImportError;
/* read_directory() cache */
static PyObject *zip_directory_cache = NULL;
/* forward decls */
static PyObject *read_directory(PyObject *archive);
static PyObject *get_data(PyObject *archive, PyObject *toc_entry);
static PyObject *get_module_code(ZipImporter *self, PyObject *fullname,
int *p_ispackage, PyObject **p_modpath);
static PyTypeObject ZipImporter_Type;
#define ZipImporter_Check(op) PyObject_TypeCheck(op, &ZipImporter_Type)
/*[clinic input]
module zipimport
class zipimport.zipimporter "ZipImporter *" "&ZipImporter_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9db8b61557d911e7]*/
#include "clinic/zipimport.c.h"
/* zipimporter.__init__
Split the "subdirectory" from the Zip archive path, lookup a matching
entry in sys.path_importer_cache, fetch the file directory from there
if found, or else read it from the archive. */
/*[clinic input]
zipimport.zipimporter.__init__
archivepath as path: object(converter="PyUnicode_FSDecoder")
A path-like object to a zipfile, or to a specific path inside
a zipfile.
/
Create a new zipimporter instance.
'archivepath' must be a path-like object to a zipfile, or to a specific path
inside a zipfile. For example, it can be '/tmp/myimport.zip', or
'/tmp/myimport.zip/mydirectory', if mydirectory is a valid directory inside
the archive.
'ZipImportError' is raised if 'archivepath' doesn't point to a valid Zip
archive.
The 'archive' attribute of the zipimporter object contains the name of the
zipfile targeted.
[clinic start generated code]*/
static int
zipimport_zipimporter___init___impl(ZipImporter *self, PyObject *path)
/*[clinic end generated code: output=141558fefdb46dc8 input=92b9ebeed1f6a704]*/
{
PyObject *files, *tmp;
PyObject *filename = NULL;
Py_ssize_t len, flen;
if (PyUnicode_READY(path) == -1)
return -1;
len = PyUnicode_GET_LENGTH(path);
if (len == 0) {
PyErr_SetString(ZipImportError, "archive path is empty");
goto error;
}
#ifdef ALTSEP
tmp = _PyObject_CallMethodId(path, &PyId_replace, "CC", ALTSEP, SEP);
if (!tmp)
goto error;
Py_DECREF(path);
path = tmp;
#endif
filename = path;
Py_INCREF(filename);
flen = len;
for (;;) {
struct stat statbuf;
int rv;
rv = _Py_stat(filename, &statbuf);
if (rv == -2)
goto error;
if (rv == 0) {
/* it exists */
if (!S_ISREG(statbuf.st_mode))
/* it's a not file */
Py_CLEAR(filename);
break;
}
Py_CLEAR(filename);
/* back up one path element */
flen = PyUnicode_FindChar(path, SEP, 0, flen, -1);
if (flen == -1)
break;
filename = PyUnicode_Substring(path, 0, flen);
if (filename == NULL)
goto error;
}
if (filename == NULL) {
PyErr_SetString(ZipImportError, "not a Zip file");
goto error;
}
if (PyUnicode_READY(filename) < 0)
goto error;
files = PyDict_GetItem(zip_directory_cache, filename);
if (files == NULL) {
files = read_directory(filename);
if (files == NULL)
goto error;
if (PyDict_SetItem(zip_directory_cache, filename, files) != 0)
goto error;
}
else
Py_INCREF(files);
Py_XSETREF(self->files, files);
/* Transfer reference */
Py_XSETREF(self->archive, filename);
filename = NULL;
/* Check if there is a prefix directory following the filename. */
if (flen != len) {
tmp = PyUnicode_Substring(path, flen+1,
PyUnicode_GET_LENGTH(path));
if (tmp == NULL)
goto error;
Py_XSETREF(self->prefix, tmp);
if (PyUnicode_READ_CHAR(path, len-1) != SEP) {
/* add trailing SEP */
tmp = PyUnicode_FromFormat("%U%c", self->prefix, SEP);
if (tmp == NULL)
goto error;
Py_SETREF(self->prefix, tmp);
}
}
else {
Py_XSETREF(self->prefix, PyUnicode_New(0, 0));
}
Py_DECREF(path);
return 0;
error:
Py_DECREF(path);
Py_XDECREF(filename);
return -1;
}
/* GC support. */
static int
zipimporter_traverse(PyObject *obj, visitproc visit, void *arg)
{
ZipImporter *self = (ZipImporter *)obj;
Py_VISIT(self->files);
return 0;
}
static void
zipimporter_dealloc(ZipImporter *self)
{
PyObject_GC_UnTrack(self);
Py_XDECREF(self->archive);
Py_XDECREF(self->prefix);
Py_XDECREF(self->files);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
zipimporter_repr(ZipImporter *self)
{
if (self->archive == NULL)
return PyUnicode_FromString("<zipimporter object \"???\">");
else if (self->prefix != NULL && PyUnicode_GET_LENGTH(self->prefix) != 0)
return PyUnicode_FromFormat("<zipimporter object \"%U%c%U\">",
self->archive, SEP, self->prefix);
else
return PyUnicode_FromFormat("<zipimporter object \"%U\">",
self->archive);
}
/* return fullname.split(".")[-1] */
static PyObject *
get_subname(PyObject *fullname)
{
Py_ssize_t len, dot;
if (PyUnicode_READY(fullname) < 0)
return NULL;
len = PyUnicode_GET_LENGTH(fullname);
dot = PyUnicode_FindChar(fullname, '.', 0, len, -1);
if (dot == -1) {
Py_INCREF(fullname);
return fullname;
} else
return PyUnicode_Substring(fullname, dot+1, len);
}
/* Given a (sub)modulename, write the potential file path in the
archive (without extension) to the path buffer. Return the
length of the resulting string.
return self.prefix + name.replace('.', os.sep) */
static PyObject*
make_filename(PyObject *prefix, PyObject *name)
{
PyObject *pathobj;
Py_UCS4 *p, *buf;
Py_ssize_t len;
len = PyUnicode_GET_LENGTH(prefix) + PyUnicode_GET_LENGTH(name) + 1;
p = buf = PyMem_New(Py_UCS4, len);
if (buf == NULL) {
PyErr_NoMemory();
return NULL;
}
if (!PyUnicode_AsUCS4(prefix, p, len, 0)) {
PyMem_Free(buf);
return NULL;
}
p += PyUnicode_GET_LENGTH(prefix);
len -= PyUnicode_GET_LENGTH(prefix);
if (!PyUnicode_AsUCS4(name, p, len, 1)) {
PyMem_Free(buf);
return NULL;
}
for (; *p; p++) {
if (*p == '.')
*p = SEP;
}
pathobj = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
buf, p-buf);
PyMem_Free(buf);
return pathobj;
}
enum zi_module_info {
MI_ERROR,
MI_NOT_FOUND,
MI_MODULE,
MI_PACKAGE
};
/* Does this path represent a directory?
on error, return < 0
if not a dir, return 0
if a dir, return 1
*/
static int
check_is_directory(ZipImporter *self, PyObject* prefix, PyObject *path)
{
PyObject *dirpath;
int res;
/* See if this is a "directory". If so, it's eligible to be part
of a namespace package. We test by seeing if the name, with an
appended path separator, exists. */
dirpath = PyUnicode_FromFormat("%U%U%c", prefix, path, SEP);
if (dirpath == NULL)
return -1;
/* If dirpath is present in self->files, we have a directory. */
res = PyDict_Contains(self->files, dirpath);
Py_DECREF(dirpath);
return res;
}
/* Return some information about a module. */
static enum zi_module_info
get_module_info(ZipImporter *self, PyObject *fullname)
{
PyObject *subname;
PyObject *path, *fullpath, *item;
struct st_zip_searchorder *zso;
if (self->prefix == NULL) {
PyErr_SetString(PyExc_ValueError,
"zipimporter.__init__() wasn't called");
return MI_ERROR;
}
subname = get_subname(fullname);
if (subname == NULL)
return MI_ERROR;
path = make_filename(self->prefix, subname);
Py_DECREF(subname);
if (path == NULL)
return MI_ERROR;
for (zso = zip_searchorder; *zso->suffix; zso++) {
fullpath = PyUnicode_FromFormat("%U%s", path, zso->suffix);
if (fullpath == NULL) {
Py_DECREF(path);
return MI_ERROR;
}
item = PyDict_GetItem(self->files, fullpath);
Py_DECREF(fullpath);
if (item != NULL) {
Py_DECREF(path);
if (zso->type & IS_PACKAGE)
return MI_PACKAGE;
else
return MI_MODULE;
}
}
Py_DECREF(path);
return MI_NOT_FOUND;
}
typedef enum {
FL_ERROR = -1, /* error */
FL_NOT_FOUND, /* no loader or namespace portions found */
FL_MODULE_FOUND, /* module/package found */
FL_NS_FOUND /* namespace portion found: */
/* *namespace_portion will point to the name */
} find_loader_result;
/* The guts of "find_loader" and "find_module".
*/
static find_loader_result
find_loader(ZipImporter *self, PyObject *fullname, PyObject **namespace_portion)
{
enum zi_module_info mi;
*namespace_portion = NULL;
mi = get_module_info(self, fullname);
if (mi == MI_ERROR)
return FL_ERROR;
if (mi == MI_NOT_FOUND) {
/* Not a module or regular package. See if this is a directory, and
therefore possibly a portion of a namespace package. */
find_loader_result result = FL_NOT_FOUND;
PyObject *subname;
int is_dir;
/* We're only interested in the last path component of fullname;
earlier components are recorded in self->prefix. */
subname = get_subname(fullname);
if (subname == NULL) {
return FL_ERROR;
}
is_dir = check_is_directory(self, self->prefix, subname);
if (is_dir < 0)
result = FL_ERROR;
else if (is_dir) {
/* This is possibly a portion of a namespace
package. Return the string representing its path,
without a trailing separator. */
*namespace_portion = PyUnicode_FromFormat("%U%c%U%U",
self->archive, SEP,
self->prefix, subname);
if (*namespace_portion == NULL)
result = FL_ERROR;
else
result = FL_NS_FOUND;
}
Py_DECREF(subname);
return result;
}
/* This is a module or package. */
return FL_MODULE_FOUND;
}
/*[clinic input]
zipimport.zipimporter.find_module
fullname: unicode
path: object = None
/
Search for a module specified by 'fullname'.
'fullname' must be the fully qualified (dotted) module name. It returns the
zipimporter instance itself if the module was found, or None if it wasn't.
The optional 'path' argument is ignored -- it's there for compatibility
with the importer protocol.
[clinic start generated code]*/
static PyObject *
zipimport_zipimporter_find_module_impl(ZipImporter *self, PyObject *fullname,
PyObject *path)
/*[clinic end generated code: output=506087f609466dc7 input=e3528520e075063f]*/
{
PyObject *namespace_portion = NULL;
PyObject *result = NULL;
switch (find_loader(self, fullname, &namespace_portion)) {
case FL_ERROR:
return NULL;
case FL_NS_FOUND:
/* A namespace portion is not allowed via find_module, so return None. */
Py_DECREF(namespace_portion);
/* FALL THROUGH */
case FL_NOT_FOUND:
result = Py_None;
break;
case FL_MODULE_FOUND:
result = (PyObject *)self;
break;
default:
PyErr_BadInternalCall();
return NULL;
}
Py_INCREF(result);
return result;
}
/*[clinic input]
zipimport.zipimporter.find_loader
fullname: unicode
path: object = None
/
Search for a module specified by 'fullname'.
'fullname' must be the fully qualified (dotted) module name. It returns the
zipimporter instance itself if the module was found, a string containing the
full path name if it's possibly a portion of a namespace package,
or None otherwise. The optional 'path' argument is ignored -- it's
there for compatibility with the importer protocol.
[clinic start generated code]*/
static PyObject *
zipimport_zipimporter_find_loader_impl(ZipImporter *self, PyObject *fullname,
PyObject *path)
/*[clinic end generated code: output=601599a43bc0f49a input=dc73f275b0d5be23]*/
{
PyObject *result = NULL;
PyObject *namespace_portion = NULL;
switch (find_loader(self, fullname, &namespace_portion)) {
case FL_ERROR:
return NULL;
case FL_NOT_FOUND: /* Not found, return (None, []) */
result = Py_BuildValue("O[]", Py_None);
break;
case FL_MODULE_FOUND: /* Return (self, []) */
result = Py_BuildValue("O[]", self);
break;
case FL_NS_FOUND: /* Return (None, [namespace_portion]) */
result = Py_BuildValue("O[O]", Py_None, namespace_portion);
Py_DECREF(namespace_portion);
return result;
default:
PyErr_BadInternalCall();
return NULL;
}
return result;
}
/*[clinic input]
zipimport.zipimporter.load_module
fullname: unicode
/
Load the module specified by 'fullname'.
'fullname' must be the fully qualified (dotted) module name. It returns the
imported module, or raises ZipImportError if it wasn't found.
[clinic start generated code]*/
static PyObject *
zipimport_zipimporter_load_module_impl(ZipImporter *self, PyObject *fullname)
/*[clinic end generated code: output=7303cebf88d47953 input=c236e2e8621f04ef]*/
{
PyObject *code = NULL, *mod, *dict;
PyObject *modpath = NULL;
int ispackage;
if (PyUnicode_READY(fullname) == -1)
return NULL;
code = get_module_code(self, fullname, &ispackage, &modpath);
if (code == NULL)
goto error;
mod = PyImport_AddModuleObject(fullname);
if (mod == NULL)
goto error;
dict = PyModule_GetDict(mod);
/* mod.__loader__ = self */
if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0)
goto error;
if (ispackage) {
/* add __path__ to the module *before* the code gets
executed */
PyObject *pkgpath, *fullpath, *subname;
int err;
subname = get_subname(fullname);
if (subname == NULL)
goto error;
fullpath = PyUnicode_FromFormat("%U%c%U%U",
self->archive, SEP,
self->prefix, subname);
Py_DECREF(subname);
if (fullpath == NULL)
goto error;
pkgpath = Py_BuildValue("[N]", fullpath);
if (pkgpath == NULL)
goto error;
err = PyDict_SetItemString(dict, "__path__", pkgpath);
Py_DECREF(pkgpath);
if (err != 0)
goto error;
}
mod = PyImport_ExecCodeModuleObject(fullname, code, modpath, NULL);
Py_CLEAR(code);
if (mod == NULL)
goto error;
if (Py_VerboseFlag)
PySys_FormatStderr("import %U # loaded from Zip %U\n",
fullname, modpath);
Py_DECREF(modpath);
return mod;
error:
Py_XDECREF(code);
Py_XDECREF(modpath);
return NULL;
}
/*[clinic input]
zipimport.zipimporter.get_filename
fullname: unicode
/
Return the filename for the specified module.
[clinic start generated code]*/
static PyObject *
zipimport_zipimporter_get_filename_impl(ZipImporter *self,
PyObject *fullname)
/*[clinic end generated code: output=c5b92b58bea86506 input=28d2eb57e4f25c8a]*/
{
PyObject *code, *modpath;
int ispackage;
/* Deciding the filename requires working out where the code
would come from if the module was actually loaded */
code = get_module_code(self, fullname, &ispackage, &modpath);
if (code == NULL)
return NULL;
Py_DECREF(code); /* Only need the path info */
return modpath;
}
/*[clinic input]
zipimport.zipimporter.is_package
fullname: unicode
/
Return True if the module specified by fullname is a package.
Raise ZipImportError if the module couldn't be found.
[clinic start generated code]*/
static PyObject *
zipimport_zipimporter_is_package_impl(ZipImporter *self, PyObject *fullname)
/*[clinic end generated code: output=c32958c2a5216ae6 input=a7ba752f64345062]*/
{
enum zi_module_info mi;
mi = get_module_info(self, fullname);
if (mi == MI_ERROR)
return NULL;
if (mi == MI_NOT_FOUND) {
PyErr_Format(ZipImportError, "can't find module %R", fullname);
return NULL;
}
return PyBool_FromLong(mi == MI_PACKAGE);
}
/*[clinic input]
zipimport.zipimporter.get_data
pathname as path: unicode
/
Return the data associated with 'pathname'.
Raise OSError if the file was not found.
[clinic start generated code]*/
static PyObject *
zipimport_zipimporter_get_data_impl(ZipImporter *self, PyObject *path)
/*[clinic end generated code: output=65dc506aaa268436 input=fa6428b74843c4ae]*/
{
PyObject *key;
PyObject *toc_entry;
Py_ssize_t path_start, path_len, len;
if (self->archive == NULL) {
PyErr_SetString(PyExc_ValueError,
"zipimporter.__init__() wasn't called");
return NULL;
}
#ifdef ALTSEP
path = _PyObject_CallMethodId((PyObject *)&PyUnicode_Type, &PyId_replace,
"OCC", path, ALTSEP, SEP);
if (!path)
return NULL;
#else
Py_INCREF(path);
#endif
if (PyUnicode_READY(path) == -1)
goto error;
path_len = PyUnicode_GET_LENGTH(path);
len = PyUnicode_GET_LENGTH(self->archive);
path_start = 0;
if (PyUnicode_Tailmatch(path, self->archive, 0, len, -1)
&& PyUnicode_READ_CHAR(path, len) == SEP) {
path_start = len + 1;
}
key = PyUnicode_Substring(path, path_start, path_len);
if (key == NULL)
goto error;
toc_entry = PyDict_GetItem(self->files, key);
if (toc_entry == NULL) {
PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, key);
Py_DECREF(key);
goto error;
}
Py_DECREF(key);
Py_DECREF(path);
return get_data(self->archive, toc_entry);
error:
Py_DECREF(path);
return NULL;
}
/*[clinic input]
zipimport.zipimporter.get_code
fullname: unicode
/
Return the code object for the specified module.
Raise ZipImportError if the module couldn't be found.
[clinic start generated code]*/
static PyObject *
zipimport_zipimporter_get_code_impl(ZipImporter *self, PyObject *fullname)
/*[clinic end generated code: output=b923c37fa99cbac4 input=2761412bc37f3549]*/
{
return get_module_code(self, fullname, NULL, NULL);
}
/*[clinic input]
zipimport.zipimporter.get_source
fullname: unicode
/
Return the source code for the specified module.
Raise ZipImportError if the module couldn't be found, return None if the
archive does contain the module, but has no source for it.
[clinic start generated code]*/
static PyObject *
zipimport_zipimporter_get_source_impl(ZipImporter *self, PyObject *fullname)
/*[clinic end generated code: output=bc059301b0c33729 input=4e4b186f2e690716]*/
{
PyObject *toc_entry;
PyObject *subname, *path, *fullpath;
enum zi_module_info mi;
mi = get_module_info(self, fullname);
if (mi == MI_ERROR)
return NULL;
if (mi == MI_NOT_FOUND) {
PyErr_Format(ZipImportError, "can't find module %R", fullname);
return NULL;
}
subname = get_subname(fullname);
if (subname == NULL)
return NULL;
path = make_filename(self->prefix, subname);
Py_DECREF(subname);
if (path == NULL)
return NULL;
if (mi == MI_PACKAGE)
fullpath = PyUnicode_FromFormat("%U%c__init__.py", path, SEP);
else
fullpath = PyUnicode_FromFormat("%U.py", path);
Py_DECREF(path);
if (fullpath == NULL)
return NULL;
toc_entry = PyDict_GetItem(self->files, fullpath);
Py_DECREF(fullpath);
if (toc_entry != NULL) {
PyObject *res, *bytes;
bytes = get_data(self->archive, toc_entry);
if (bytes == NULL)
return NULL;
res = PyUnicode_FromStringAndSize(PyBytes_AS_STRING(bytes),
PyBytes_GET_SIZE(bytes));
Py_DECREF(bytes);
return res;
}
/* we have the module, but no source */
Py_RETURN_NONE;
}
/*[clinic input]
zipimport.zipimporter.get_resource_reader
fullname: unicode
/
Return the ResourceReader for a package in a zip file.
If 'fullname' is a package within the zip file, return the 'ResourceReader'
object for the package. Otherwise return None.
[clinic start generated code]*/
static PyObject *
zipimport_zipimporter_get_resource_reader_impl(ZipImporter *self,
PyObject *fullname)
/*[clinic end generated code: output=5e367d431f830726 input=bfab94d736e99151]*/
{
PyObject *module = PyImport_ImportModule("importlib.resources");
if (module == NULL) {
return NULL;
}
PyObject *retval = PyObject_CallMethod(
module, "_zipimport_get_resource_reader",
"OO", (PyObject *)self, fullname);
Py_DECREF(module);
return retval;
}
static PyMethodDef zipimporter_methods[] = {
ZIPIMPORT_ZIPIMPORTER_FIND_MODULE_METHODDEF
ZIPIMPORT_ZIPIMPORTER_FIND_LOADER_METHODDEF
ZIPIMPORT_ZIPIMPORTER_LOAD_MODULE_METHODDEF
ZIPIMPORT_ZIPIMPORTER_GET_FILENAME_METHODDEF
ZIPIMPORT_ZIPIMPORTER_IS_PACKAGE_METHODDEF
ZIPIMPORT_ZIPIMPORTER_GET_DATA_METHODDEF
ZIPIMPORT_ZIPIMPORTER_GET_CODE_METHODDEF
ZIPIMPORT_ZIPIMPORTER_GET_SOURCE_METHODDEF
ZIPIMPORT_ZIPIMPORTER_GET_RESOURCE_READER_METHODDEF
{NULL, NULL} /* sentinel */
};
static PyMemberDef zipimporter_members[] = {
{"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY},
{"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY},
{"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY},
{NULL}
};
#define DEFERRED_ADDRESS(ADDR) 0
static PyTypeObject ZipImporter_Type = {
PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
"zipimport.zipimporter",
sizeof(ZipImporter),
0, /* tp_itemsize */
(destructor)zipimporter_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc)zipimporter_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Py_TPFLAGS_HAVE_GC, /* tp_flags */
zipimport_zipimporter___init____doc__, /* tp_doc */
zipimporter_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
zipimporter_methods, /* tp_methods */
zipimporter_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)zipimport_zipimporter___init__, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
PyType_GenericNew, /* tp_new */
PyObject_GC_Del, /* tp_free */
};
/* implementation */
/* Given a buffer, return the unsigned int that is represented by the first
4 bytes, encoded as little endian. This partially reimplements
marshal.c:r_long() */
static unsigned int
get_uint32(const unsigned char *buf)
{
unsigned int x;
x = buf[0];
x |= (unsigned int)buf[1] << 8;
x |= (unsigned int)buf[2] << 16;
x |= (unsigned int)buf[3] << 24;
return x;
}
/* Given a buffer, return the unsigned int that is represented by the first
2 bytes, encoded as little endian. This partially reimplements
marshal.c:r_short() */
static unsigned short
get_uint16(const unsigned char *buf)
{
unsigned short x;
x = buf[0];
x |= (unsigned short)buf[1] << 8;
return x;
}
static void
set_file_error(PyObject *archive, int eof)
{
if (eof) {
PyErr_SetString(PyExc_EOFError, "EOF read where not expected");
}
else {
PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, archive);
}
}
/*
read_directory(archive) -> files dict (new reference)
Given a path to a Zip archive, build a dict, mapping file names
(local to the archive, using SEP as a separator) to toc entries.
A toc_entry is a tuple:
(__file__, # value to use for __file__, available for all files,
# encoded to the filesystem encoding
compress, # compression kind; 0 for uncompressed
data_size, # size of compressed data on disk
file_size, # size of decompressed data
file_offset, # offset of file header from start of archive
time, # mod time of file (in dos format)
date, # mod data of file (in dos format)
crc, # crc checksum of the data
)
Directories can be recognized by the trailing SEP in the name,
data_size and file_offset are 0.
*/
static PyObject *
read_directory(PyObject *archive)
{
PyObject *files = NULL;
FILE *fp;
unsigned short flags, compress, time, date, name_size;
unsigned int crc, data_size, file_size, header_size, header_offset;
unsigned long file_offset, header_position;
unsigned long arc_offset; /* Absolute offset to start of the zip-archive. */
unsigned int count, i;
unsigned char buffer[46];
char name[MAXPATHLEN + 5];
PyObject *nameobj = NULL;
PyObject *path;
const char *charset;
int bootstrap;
const char *errmsg = NULL;
fp = _Py_fopen_obj(archive, "rb");
if (fp == NULL) {
if (PyErr_ExceptionMatches(PyExc_OSError)) {
_PyErr_FormatFromCause(ZipImportError,
"can't open Zip file: %R", archive);
}
return NULL;
}
if (fseek(fp, -22, SEEK_END) == -1) {
goto file_error;
}
header_position = (unsigned long)ftell(fp);
if (header_position == (unsigned long)-1) {
goto file_error;
}
assert(header_position <= (unsigned long)LONG_MAX);
if (fread(buffer, 1, 22, fp) != 22) {
goto file_error;
}
if (get_uint32(buffer) != 0x06054B50u) {
/* Bad: End of Central Dir signature */
errmsg = "not a Zip file";
goto invalid_header;
}
header_size = get_uint32(buffer + 12);
header_offset = get_uint32(buffer + 16);
if (header_position < header_size) {
errmsg = "bad central directory size";
goto invalid_header;
}
if (header_position < header_offset) {
errmsg = "bad central directory offset";
goto invalid_header;
}
if (header_position - header_size < header_offset) {
errmsg = "bad central directory size or offset";
goto invalid_header;
}