id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
1,300
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/backends/django/db/backend.py
djedi.backends.django.db.backend.DjangoModelStorageBackend
class DjangoModelStorageBackend(DatabaseBackend): scheme = "db" def __init__(self, **config): super().__init__(**config) def get_many(self, uris): storage_keys = {self._build_key(uri): uri for uri in uris} stored_nodes = Node.objects.filter(key__in=storage_keys.keys()) stored_nodes = stored_nodes.values_list( "key", "content", "plugin", "version", "is_published", "meta" ) # Filter matching nodes nodes = {} for key, content, plugin, version, is_published, meta in stored_nodes: uri = storage_keys[key] # Assert requested plugin matches if uri.ext in (None, plugin): # Assert version matches or node is published if (uri.version == version) or (is_published and not uri.version): meta = self._decode_meta(meta, is_published=is_published) nodes[uri] = { "uri": uri.clone(ext=plugin, version=version), "content": content, "meta": meta, } return nodes def publish(self, uri, **meta): node = self._get(uri) if not node.is_published: # Assign version number if not node.version.isdigit(): revisions = Node.objects.filter(key=node.key).values_list( "version", flat=True ) version = self._get_next_version(revisions) node.version = version # Un publish any other revision Node.objects.filter(key=node.key).update(is_published=False) # Publish this version self._update_meta(node, meta) node.is_published = True node.save() return self._serialize(uri, node) def get_revisions(self, uri): key = self._build_key(uri) nodes = Node.objects.filter(key=key).order_by("date_created") revisions = nodes.values_list("plugin", "version", "is_published") return [ (key.clone(ext=plugin, version=version), is_published) for plugin, version, is_published in revisions ] def _get(self, uri): key = self._build_key(uri) nodes = Node.objects.filter(key=key) if uri.ext: nodes = nodes.filter(plugin=uri.ext) if uri.version: nodes = nodes.filter(version=uri.version) else: nodes = nodes.filter(is_published=True) try: return nodes.get() except Node.DoesNotExist: raise NodeDoesNotExist('Node for uri "%s" does not exist' % uri) def _create(self, uri, content, **meta): try: meta = self._encode_meta(meta) return Node.objects.create( key=self._build_key(uri), content=content, plugin=uri.ext, version=uri.version, is_published=False, meta=meta, ) except IntegrityError as e: raise PersistenceError(f'Failed to create node for uri "{uri}"; {e}') def _update(self, uri, content, **meta): node = self._get(uri) self._update_meta(node, meta) node.content = content node.plugin = uri.ext node.version = uri.version node.save() return node def _delete(self, node): node.delete() def _serialize(self, uri, node): meta = self._decode_meta(node.meta, is_published=node.is_published) return { "uri": uri.clone(ext=node.plugin, version=node.version), "content": node.content, "meta": meta, } def _update_meta(self, node, meta): node.meta = self._merge_meta(node.meta, meta)
class DjangoModelStorageBackend(DatabaseBackend): def __init__(self, **config): pass def get_many(self, uris): pass def publish(self, uri, **meta): pass def get_revisions(self, uri): pass def _get(self, uri): pass def _create(self, uri, content, **meta): pass def _update(self, uri, content, **meta): pass def _delete(self, node): pass def _serialize(self, uri, node): pass def _update_meta(self, node, meta): pass
11
0
11
1
9
1
2
0.07
1
2
1
1
10
0
10
10
117
22
89
27
78
6
66
26
55
4
1
3
19
1,301
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/backends/django/db/__init__.py
djedi.backends.django.db.Backend
class Backend(DjangoModelStorageBackend): pass
class Backend(DjangoModelStorageBackend): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
2
0
0
1,302
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/backends/django/cache/backend.py
djedi.backends.django.cache.backend.DjangoCacheBackend
class DjangoCacheBackend(CacheBackend): def __init__(self, **config): """ Get cache backend. Look for djedi specific cache first, then fallback on default """ super().__init__(**config) try: cache_name = self.config.get("NAME", "djedi") cache = caches[cache_name] except (InvalidCacheBackendError, ValueError): from django.core.cache import cache self._cache = cache def clear(self): self._cache.clear() def _get(self, key): return self._cache.get(key) def _get_many(self, keys): return self._cache.get_many(keys) def _set(self, key, value): # TODO: Fix eternal timeout like viewlet self._cache.set(key, value, timeout=None) def _set_many(self, data): # TODO: Fix eternal timeout like viewlet self._cache.set_many(data, timeout=None) def _delete(self, key): self._cache.delete(key) def _delete_many(self, keys): self._cache.delete_many(keys) def _encode_content(self, uri, content): """ Join node uri and content as string and convert to bytes to ensure no pickling in memcached. """ if content is None: content = self.NONE return smart_bytes("|".join([str(uri), content])) def _decode_content(self, content): """ Split node string to uri and content and convert back to unicode. """ content = smart_str(content) uri, _, content = content.partition("|") if content == self.NONE: content = None return uri or None, content
class DjangoCacheBackend(CacheBackend): def __init__(self, **config): ''' Get cache backend. Look for djedi specific cache first, then fallback on default ''' pass def clear(self): pass def _get(self, key): pass def _get_many(self, keys): pass def _set(self, key, value): pass def _set_many(self, data): pass def _delete(self, key): pass def _delete_many(self, keys): pass def _encode_content(self, uri, content): ''' Join node uri and content as string and convert to bytes to ensure no pickling in memcached. ''' pass def _decode_content(self, content): ''' Split node string to uri and content and convert back to unicode. ''' pass
11
3
5
0
3
1
1
0.33
1
3
0
1
10
1
10
10
55
11
33
16
21
11
33
16
21
2
1
1
13
1,303
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/backends/django/cache/backend.py
djedi.backends.django.cache.backend.DebugLocMemCache
class DebugLocMemCache(LocMemCache): def __init__(self, *args, **kwargs): self.calls = 0 self.hits = 0 self.misses = 0 self.sets = 0 super().__init__(*args, **kwargs) def get(self, key, default=None, version=None, **kwargs): result = super().get(key, default=default, version=version) if kwargs.get("count", True): self.calls += 1 if result is None: self.misses += 1 else: self.hits += 1 return result def get_many(self, keys, version=None): d = {} for k in keys: val = self.get(k, version=version, count=False) if val is not None: d[k] = val hits = len(d) self.calls += 1 self.hits += hits self.misses += len(keys) - hits return d def set(self, *args, **kwargs): super().set(*args, **kwargs) self.calls += 1 self.sets += 1 def set_many(self, data, *args, **kwargs): result = super().set_many(data, *args, **kwargs) self.calls -= len(data) # Remove calls from set() self.calls += 1 return result
class DebugLocMemCache(LocMemCache): def __init__(self, *args, **kwargs): pass def get(self, key, default=None, version=None, **kwargs): pass def get_many(self, keys, version=None): pass def set(self, *args, **kwargs): pass def set_many(self, data, *args, **kwargs): pass
6
0
7
0
7
0
2
0.03
1
1
0
0
5
4
5
5
40
4
36
16
30
1
35
16
29
3
1
2
9
1,304
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/backends/django/cache/__init__.py
djedi.backends.django.cache.Backend
class Backend(DjangoCacheBackend): pass
class Backend(DjangoCacheBackend): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
2
0
0
1,305
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/apps.py
djedi.apps.DjediConfig
class DjediConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "djedi" verbose_name = "Djedi CMS"
class DjediConfig(AppConfig): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
4
0
4
4
3
0
4
4
3
0
1
0
0
1,306
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/admin/mixins.py
djedi.admin.mixins.JSONResponseMixin
class JSONResponseMixin: """ A mixin that can be used to render a JSON response. """ response_class = HttpResponse def render_to_json(self, context, **response_kwargs): """ Returns a JSON response, transforming 'context' to make the payload. """ response_kwargs["content_type"] = "application/json" return self.response_class( self.convert_context_to_json(context), **response_kwargs ) def convert_context_to_json(self, context): """Convert the context dictionary into a JSON object""" return json.dumps(context, indent=4, for_json=True)
class JSONResponseMixin: ''' A mixin that can be used to render a JSON response. ''' def render_to_json(self, context, **response_kwargs): ''' Returns a JSON response, transforming 'context' to make the payload. ''' pass def convert_context_to_json(self, context): '''Convert the context dictionary into a JSON object''' pass
3
3
6
0
4
2
1
0.78
0
0
0
6
2
0
2
2
19
3
9
4
6
7
7
4
4
1
0
0
2
1,307
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/admin/mixins.py
djedi.admin.mixins.DjediContextMixin
class DjediContextMixin: def get_context_data(self, **context): theme = settings.THEME if "/" not in theme: theme = f"{django_settings.STATIC_URL}djedi/themes/{theme}/theme.css" context["THEME"] = theme context["VERSION"] = djedi.__version__ return context
class DjediContextMixin: def get_context_data(self, **context): pass
2
0
10
3
7
0
2
0
0
0
0
2
1
0
1
1
11
3
8
3
6
0
8
3
6
2
0
1
2
1,308
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/admin/exceptions.py
djedi.admin.exceptions.InvalidNodeData
class InvalidNodeData(Exception): pass
class InvalidNodeData(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
1,309
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/admin/cms.py
djedi.admin.cms.DjediCMS
class DjediCMS(DjediContextMixin, View): @xframe_options_exempt def get(self, request): if has_permission(request): return render( request, "djedi/cms/cms.html", self.get_context_data(), using="django" ) else: raise PermissionDenied
class DjediCMS(DjediContextMixin, View): @xframe_options_exempt def get(self, request): pass
3
0
7
0
7
0
2
0
2
0
0
0
1
0
1
2
9
0
9
3
6
0
5
2
3
2
1
1
2
1,310
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/admin/cms.py
djedi.admin.cms.Admin
class Admin(ModelAdmin): verbose_name = "CMS" verbose_name_plural = verbose_name def get_urls(self): return [ re_path(r"^", include("djedi.admin.urls", namespace="djedi")), re_path( r"", lambda: None, name="djedi_cms_changelist" ), # Placeholder to show change link to CMS in admin ] def has_change_permission(self, request, obj=None): return has_permission(request) def has_add_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False # Hide Djedi in the admin, since that view is not finished yet. # This only works in Django 1.8+, but shouldn't break older versions. def has_module_permission(self, request): return False
class Admin(ModelAdmin): def get_urls(self): pass def has_change_permission(self, request, obj=None): pass def has_add_permission(self, request, obj=None): pass def has_delete_permission(self, request, obj=None): pass def has_module_permission(self, request): pass
6
0
3
0
3
0
1
0.17
1
0
0
0
5
0
5
5
25
5
18
8
12
3
13
8
7
1
1
0
5
1,311
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/admin/api.py
djedi.admin.api.RevisionsApi
class RevisionsApi(JSONResponseMixin, APIView): def get(self, request, uri): """ List uri revisions. JSON Response: [[uri, state], ...] """ uri = self.decode_uri(uri) revisions = cio.revisions(uri) # Convert tuples to lists revisions = [list(revision) for revision in revisions] return self.render_to_json(revisions)
class RevisionsApi(JSONResponseMixin, APIView): def get(self, request, uri): ''' List uri revisions. JSON Response: [[uri, state], ...] ''' pass
2
1
12
1
5
6
1
1
2
1
0
0
1
0
1
7
13
1
6
3
4
6
6
3
4
1
2
0
1
1,312
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/admin/api.py
djedi.admin.api.RenderApi
class RenderApi(APIView): def post(self, request, ext): """ Render data for plugin and return text response. """ try: plugin = plugins.get(ext) data, meta = self.get_post_data(request) data = plugin.load(data) except UnknownPlugin: raise Http404 else: content = plugin.render(data) return self.render_to_response(content)
class RenderApi(APIView): def post(self, request, ext): ''' Render data for plugin and return text response. ''' pass
2
1
13
0
10
3
2
0.27
1
0
0
0
1
0
1
5
14
0
11
5
9
3
11
5
9
2
2
1
2
1,313
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/admin/api.py
djedi.admin.api.PublishApi
class PublishApi(JSONResponseMixin, APIView): def put(self, request, uri): """ Publish versioned uri. JSON Response: {uri: x, content: y} """ uri = self.decode_uri(uri) node = cio.publish(uri) if not node: raise Http404 return self.render_to_json(node)
class PublishApi(JSONResponseMixin, APIView): def put(self, request, uri): ''' Publish versioned uri. JSON Response: {uri: x, content: y} ''' pass
2
1
14
3
6
5
2
0.71
2
0
0
0
1
0
1
7
15
3
7
3
5
5
7
3
5
2
2
1
2
1,314
5monkeys/djedi-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_djedi-cms/djedi/admin/api.py
djedi.admin.api.NodeApi
class NodeApi(JSONResponseMixin, APIView): @method_decorator(never_cache) def get(self, request, uri): """ Return published node or specified version. JSON Response: {uri: x, content: y} """ uri = self.decode_uri(uri) node = cio.get(uri, lazy=False) if node.content is None: raise Http404 return self.render_to_json({"uri": node.uri, "content": node.content}) def post(self, request, uri): """ Set node data for uri, return rendered content. JSON Response: {uri: x, content: y} """ uri = self.decode_uri(uri) data, meta = self.get_post_data(request) meta["author"] = auth.get_username(request) node = cio.set(uri, data, publish=False, **meta) return self.render_to_json(node) def delete(self, request, uri): """ Delete versioned uri and return empty text response on success. """ uri = self.decode_uri(uri) uris = cio.delete(uri) if uri not in uris: raise Http404 return self.render_to_response()
class NodeApi(JSONResponseMixin, APIView): @method_decorator(never_cache) def get(self, request, uri): ''' Return published node or specified version. JSON Response: {uri: x, content: y} ''' pass def post(self, request, uri): ''' Set node data for uri, return rendered content. JSON Response: {uri: x, content: y} ''' pass def delete(self, request, uri): ''' Delete versioned uri and return empty text response on success. ''' pass
5
3
12
2
6
4
2
0.65
2
1
0
0
3
0
3
9
41
8
20
9
15
13
19
8
15
2
2
1
5
1,315
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/plugins/form.py
djedi.plugins.form.FormsBasePlugin
class FormsBasePlugin(DjediPlugin): ext = None @property def forms(self): return {} def get_editor_context(self, **context): context.update({"forms": {tab: form() for tab, form in self.forms.items()}}) return context def save(self, data, dumps=True): data = self.collect_forms_data(data) return json.dumps(data) if dumps else data def collect_forms_data(self, data): return { deprefix(field): data.get(deprefix(field)) for tab, form in self.forms.items() for field in form.base_fields.keys() }
class FormsBasePlugin(DjediPlugin): @property def forms(self): pass def get_editor_context(self, **context): pass def save(self, data, dumps=True): pass def collect_forms_data(self, data): pass
6
0
4
0
4
0
1
0
1
0
0
1
4
0
4
5
22
5
17
8
11
0
12
6
7
2
2
0
5
1,316
5monkeys/djedi-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_djedi-cms/djedi/backends/django/db/models.py
djedi.backends.django.db.models.Node.Meta
class Meta: db_table = "djedi_node"
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
1,317
5monkeys/djedi-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_djedi-cms/djedi/plugins/form.py
djedi.plugins.form.get_custom_render_widget.CustomRenderWidget
class CustomRenderWidget(cls): def render(self, *args, **kwargs): name = kwargs.pop("name", None) if not name: name = args[0] args = args[1:] name = deprefix(name) return super().render("data[%s]" % name, *args, **kwargs)
class CustomRenderWidget(cls): def render(self, *args, **kwargs): pass
2
0
10
3
7
0
2
0
1
1
0
0
1
0
1
1
11
3
8
3
6
0
8
3
6
2
1
1
2
1,318
5monkeys/djedi-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_djedi-cms/djedi/tests/test_templatetags.py
djedi.tests.test_templatetags.TagTest.test_djedi_admin_tag.RequestMock
class RequestMock: def __init__(self, user): self.user = user
class RequestMock: def __init__(self, user): pass
2
0
2
0
2
0
1
0
0
0
0
0
1
1
1
1
3
0
3
3
1
0
3
3
1
1
0
0
1
1,319
5monkeys/djedi-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_djedi-cms/djedi/rest/api.py
djedi.rest.api.NodesApi
class NodesApi(APIView): """ JSON Response: {uri: content, uri: content, ...} """ @method_decorator(never_cache) def post(self, request): # Disable caching gets in CachePipe, defaults through this api is not trusted cio.conf.settings.configure( local=True, CACHE={"PIPE": {"CACHE_ON_GET": False}}) nodes = [] for uri, default in json.loads(request.body).items(): node = cio.get(uri, default=default) nodes.append(node) data = {node.uri: node.content for node in nodes} return self.render_to_json(data)
class NodesApi(APIView): ''' JSON Response: {uri: content, uri: content, ...} ''' @method_decorator(never_cache) def post(self, request): pass
3
1
12
3
8
1
2
0.5
1
0
0
0
1
0
1
4
19
4
10
7
7
5
9
6
7
2
2
1
2
1,320
5monkeys/djedi-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_djedi-cms/djedi/templatetags/template.py
djedi.templatetags.template.lazy_tag.dec.SimpleNode
class SimpleNode(Node): def __init__(self, takes_context, args, kwargs): self.takes_context = takes_context self.args = args self.kwargs = kwargs resolved_args, resolved_kwargs = self.get_resolved_arguments( Context({}) ) self.resolved_args = resolved_args self.resolved_kwargs = resolved_kwargs self.render_func = func(*resolved_args, **resolved_kwargs) def get_resolved_arguments(self, context): resolved_args = [var.resolve(context) for var in self.args] if self.takes_context: resolved_args = [context] + resolved_args resolved_kwargs = { k: v.resolve(context) for k, v in self.kwargs.items() } return resolved_args, resolved_kwargs def render(self, context): return self.render_func(context)
class SimpleNode(Node): def __init__(self, takes_context, args, kwargs): pass def get_resolved_arguments(self, context): pass def render(self, context): pass
4
0
7
1
7
0
1
0
1
0
0
0
3
6
3
3
25
4
21
13
17
0
17
13
13
2
1
1
4
1,321
5monkeys/djedi-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_djedi-cms/djedi/tests/test_admin.py
djedi.tests.test_admin.PanelTest
class PanelTest(ClientTest): def test_embed(self): url = reverse("index") response = self.client.get(url) self.assertIn("Djedi Test", smart_str(response.content)) self.assertIn("window.DJEDI_NODES", smart_str(response.content)) self.assertIn("i18n://sv-se@foo/bar.txt", smart_str(response.content)) self.assertIn("</body>", smart_str(response.content).lower()) def test_middleware(self): with self.settings( MIDDLEWARE_CLASSES=[ "djedi.middleware.translation.DjediTranslationMiddleware", ], MIDDLEWARE=[ "djedi.middleware.translation.DjediTranslationMiddleware", ], ): url = reverse("index") response = self.client.get(url) self.assertNotIn("window.DJEDI_NODES", smart_str(response.content)) def test_cms(self): url = reverse("admin:djedi:cms") response = self.client.get(url) self.assertIn("<title>djedi cms</title>", smart_str(response.content)) self.assertNotIn("document.domain", smart_str(response.content)) self.assertNotIn("None", smart_str(response.content)) with cio.conf.settings(XSS_DOMAIN="foobar.se"): response = self.client.get(url) self.assertIn(b'document.domain = "foobar.se"', response.content) @skip("Unfinished admin view is hidden") def test_django_admin(self): # pragma: no cover # Patch django admin index from django.contrib.admin.templatetags.log import AdminLogNode _render = AdminLogNode.render AdminLogNode.render = lambda x, y: None url = reverse("admin:index") response = self.client.get(url) cms_url = reverse("admin:djedi:cms") self.assertIn('<a href="%s">CMS</a>' % cms_url, smart_str(response.content)) # Rollback patch AdminLogNode.render = _render
class PanelTest(ClientTest): def test_embed(self): pass def test_middleware(self): pass def test_cms(self): pass @skip("Unfinished admin view is hidden") def test_django_admin(self): pass
6
0
11
1
9
1
1
0.08
1
0
0
0
4
0
4
14
48
7
39
17
32
3
31
16
25
1
3
1
4
1,322
5monkeys/djedi-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_djedi-cms/djedi/tests/test_templatetags.py
djedi.tests.test_templatetags.TagTest
class TagTest(DjediTest, AssertionMixin): def render(self, source, context=None): source = "{% load djedi_tags %}" + source.strip() return engines["django"].from_string(source).render(context).strip() def test_node_tag(self): html = self.render("{% node 'page/title' edit=False %}") assert html == "" cio.set("i18n://sv-se@page/title.txt", "Djedi") cio.set("i18n://sv-se@page/body.txt", "Lightning fast!") with self.assertCache(calls=1, misses=0): with self.assertDB(calls=0): html = self.render( "<h1>{% node 'page/title' edit=False %}</h1><p>{% node 'page/body' edit=False %}</p>" ) assert html == "<h1>Djedi</h1><p>Lightning fast!</p>" cache.clear() with self.assertCache(calls=1, misses=2): with self.assertDB(calls=1): html = self.render( "<h1>{% node 'page/title' edit=False %}</h1><p>{% node 'page/body' %}</p>" ) assert ( html == '<h1>Djedi</h1><p><span data-i18n="sv-se@page/body">Lightning fast!</span></p>' ) html = self.render("{% node 'foo/bar' default='bogus' %}") assert html == '<span data-i18n="sv-se@foo/bar">bogus</span>' html = self.render("{% node 'l10n://foo/bar' default='bogus' %}") self.assertEqual(html, '<span data-i18n="djedi@foo/bar">bogus</span>') def test_node_tag_with_default_scheme(self): cio.set("i18n://sv-se@page/title.txt", "Swedish Djedi") html = self.render("{% node 'page/title' edit=False %}") assert html == "Swedish Djedi" with self.settings(DJEDI={"URI_DEFAULT_SCHEME": "l10n"}): html = self.render("{% node 'page/title' edit=False %}") assert html == "" cio.set("l10n://djedi@page/title.txt", "Local Djedi") html = self.render("{% node 'page/title' edit=False %}") assert html == "Local Djedi" def test_blocknode_tag(self): with self.assertRaises(TemplateSyntaxError): self.render("{% blocknode 'page/body' arg %}{% endblocknode %}") html = self.render( """ {% blocknode 'page/body.md' edit=False %} # Djedi Lightning *fast*! {% endblocknode %} """ ) self.assertRenderedMarkdown(html, "# Djedi\nLightning *fast*!") cio.set("i18n://sv-se@page/body.txt", "Lightning fast!") html = self.render( """ {% blocknode "page/body" %} Lorem ipsum {% endblocknode %} """ ) assert html == '<span data-i18n="sv-se@page/body">Lightning fast!</span>' cio.set("i18n://sv-se@page/body.txt", "") html = self.render( "{% blocknode 'page/body' edit=False %}Lorem ipsum{% endblocknode %}" ) assert html == "" def test_blocknode_with_context(self): cio.set("i18n://sv-se@page/title.txt", "Hej {name}!") source = """ {% blocknode 'page/title' edit=False name=user.get_full_name %} Hello {name}! {% endblocknode %} """ context = {"user": User(first_name="Jonas", last_name="Lundberg")} html = self.render(source, context) assert html == "Hej Jonas Lundberg!" with cio.env(i18n="en-us"): html = self.render(source, context) assert html == "Hello Jonas Lundberg!" html = self.render( """ {% blocknode 'page/title' edit=False %} Hello {name}! {% endblocknode %} """ ) assert html == "Hej {name}!" def test_collected_nodes(self): source = """ {% node 'page/title' edit=False %} {% node 'page/title' default='fallback' edit=False %} {% node 'page/body' edit=False %} """ pipeline.history.clear() self.render(source) assert len(pipeline.history) == 2 def test_invalid_lazy_tag(self): with self.assertRaises(TemplateSyntaxError): register.lazy_tag("") def test_lazy_tag(self): @register.lazy_tag def foo(): return lambda _: "bar" html = self.render("{% foo %}") assert html == "bar" @register.lazy_tag() def bar(): return lambda _: "foo" html = self.render("{% bar %}") assert html == "foo" def test_djedi_admin_tag(self): source = """ {% load djedi_admin %} {% djedi_admin %} """ user = User(first_name="Jonas", last_name="Lundberg") class RequestMock: def __init__(self, user): self.user = user context = {"request": RequestMock(user=user)} html = self.render(source, context) assert html == "" user.is_superuser = True html = self.render(source, context) assert "<script>window.DJEDI_NODES = {};</script>" in html
class TagTest(DjediTest, AssertionMixin): def render(self, source, context=None): pass def test_node_tag(self): pass def test_node_tag_with_default_scheme(self): pass def test_blocknode_tag(self): pass def test_blocknode_with_context(self): pass def test_collected_nodes(self): pass def test_invalid_lazy_tag(self): pass def test_lazy_tag(self): pass @register.lazy_tag def foo(): pass @register.lazy_tag() def bar(): pass def test_djedi_admin_tag(self): pass class RequestMock: def __init__(self, user): pass
16
0
13
2
11
0
1
0.02
2
2
1
0
9
0
9
16
153
29
123
29
107
2
83
27
69
1
2
2
12
1,323
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/middleware/translation.py
djedi.middleware.translation.DjediTranslationMiddleware
class DjediTranslationMiddleware(DjediAdminMiddleware, TranslationMixin): def process_request(self, request): super().process_request(request) self.activate_language()
class DjediTranslationMiddleware(DjediAdminMiddleware, TranslationMixin): def process_request(self, request): pass
2
0
3
0
3
0
1
0
2
1
0
0
1
0
1
11
4
0
4
2
2
0
4
2
2
1
2
0
1
1,324
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/migrations/0001_initial.py
djedi.migrations.0001_initial.Migration
class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name="Node", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("key", models.CharField(max_length=255, db_index=True)), ("content", models.TextField(blank=True)), ("plugin", models.CharField(max_length=8)), ("version", models.CharField(max_length=255)), ("is_published", models.BooleanField(default=False)), ("meta", models.TextField(null=True, blank=True)), ("date_created", models.DateTimeField(auto_now_add=True)), ], options={ "db_table": "djedi_node", }, bases=(models.Model,), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
30
1
29
3
28
0
3
3
2
0
1
0
0
1,325
5monkeys/djedi-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_djedi-cms/djedi/admin/api.py
djedi.admin.api.NodeEditor
class NodeEditor(JSONResponseMixin, DjediContextMixin, APIView): @method_decorator(never_cache) @method_decorator(xframe_options_exempt) def get(self, request, uri): try: uri = self.decode_uri(uri) uri = URI(uri) plugin = plugins.resolve(uri) plugin_context = self.get_context_data(uri=uri) if isinstance(plugin, DjediPlugin): plugin_context = plugin.get_editor_context(**plugin_context) except UnknownPlugin: raise Http404 else: return self.render_plugin(request, plugin_context) @method_decorator(never_cache) def post(self, request, uri): uri = self.decode_uri(uri) data, meta = self.get_post_data(request) meta["author"] = auth.get_username(request) node = cio.set(uri, data, publish=False, **meta) context = cio.load(node.uri) context["content"] = node.content # is_ajax call? if request.META.get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest": return self.render_to_json(context) else: return self.render_plugin(request, context) def render_plugin(self, request, context): return TemplateResponse( request, [ "djedi/plugins/%s/editor.html" % context["uri"].ext, "djedi/plugins/base/editor.html", ], self.get_context_data(**context), using="django", )
class NodeEditor(JSONResponseMixin, DjediContextMixin, APIView): @method_decorator(never_cache) @method_decorator(xframe_options_exempt) def get(self, request, uri): pass @method_decorator(never_cache) def post(self, request, uri): pass def render_plugin(self, request, context): pass
7
0
13
1
11
0
2
0.03
3
2
1
0
3
0
3
10
44
6
37
11
30
1
25
9
21
3
2
2
6
1,326
5monkeys/djedi-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_djedi-cms/djedi/admin/api.py
djedi.admin.api.LoadApi
class LoadApi(JSONResponseMixin, APIView): @method_decorator(never_cache) def get(self, request, uri): """ Load raw node source from storage. JSON Response: {uri: x, data: y} """ uri = self.decode_uri(uri) node = cio.load(uri) return self.render_to_json(node)
class LoadApi(JSONResponseMixin, APIView): @method_decorator(never_cache) def get(self, request, uri): ''' Load raw node source from storage. JSON Response: {uri: x, data: y} ''' pass
3
1
10
1
4
5
1
0.83
2
0
0
0
1
0
1
7
12
1
6
4
3
5
5
3
3
1
2
0
1
1,327
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/tests/base.py
djedi.tests.base.AssertionMixin
class AssertionMixin: def assertKeys(self, dict, *keys): self.assertEqual(set(dict.keys()), set(keys)) @contextmanager def assertCache(self, calls=-1, hits=-1, misses=-1, sets=-1): from cio.backends import cache _cache = cache.backend._cache _cache.calls = 0 _cache.hits = 0 _cache.misses = 0 _cache.sets = 0 yield if calls >= 0: assert _cache.calls == calls, f"{_cache.calls} != {calls}" if hits >= 0: assert _cache.hits == hits, f"{_cache.hits} != {hits}" if misses >= 0: assert _cache.misses == misses, f"{_cache.misses} != {misses}" if sets >= 0: assert _cache.sets == sets, f"{_cache.sets} != {sets}" @contextmanager def assertDB(self, calls=-1, selects=-1, inserts=-1, updates=-1): from django.db import connection pre_debug_cursor = getattr(connection, DEBUG_CURSOR_ATTR) setattr(connection, DEBUG_CURSOR_ATTR, True) pre_num_queries = len(connection.queries) yield queries = connection.queries[pre_num_queries:] num_queries = len(queries) setattr(connection, DEBUG_CURSOR_ATTR, pre_debug_cursor) if calls >= 0: assert num_queries == calls, f"{num_queries} != {calls}" if selects >= 0: num_selects = len([q for q in queries if q["sql"].startswith("SELECT")]) assert num_selects == selects, f"{num_selects} != {selects}" if inserts >= 0: num_inserts = len([q for q in queries if q["sql"].startswith("INSERT")]) assert num_inserts == inserts, f"{num_inserts} != {inserts}" if updates >= 0: num_updates = len([q for q in queries if q["sql"].startswith("UPDATE")]) assert num_updates == updates, f"{num_updates} != {updates}" def assertRenderedMarkdown(self, value, source): if cio.PY26: self.assertEqual(value, source) # Markdown lacks Support for python 2.6 else: from markdown import markdown rendered = markdown(source) self.assertEqual(value, rendered)
class AssertionMixin: def assertKeys(self, dict, *keys): pass @contextmanager def assertCache(self, calls=-1, hits=-1, misses=-1, sets=-1): pass @contextmanager def assertDB(self, calls=-1, selects=-1, inserts=-1, updates=-1): pass def assertRenderedMarkdown(self, value, source): pass
7
0
14
2
11
0
3
0.02
0
1
0
2
4
0
4
4
60
12
48
19
38
1
45
17
37
5
0
1
13
1,328
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/tests/base.py
djedi.tests.base.ClientTest
class ClientTest(DjediTest, UserMixin, AssertionMixin): def setUp(self): super().setUp() master = self.create_djedi_master() client = Client(enforce_csrf_checks=True) client.login(username=master.username, password="test") self.client = client
class ClientTest(DjediTest, UserMixin, AssertionMixin): def setUp(self): pass
2
0
6
0
6
0
1
0
3
1
0
3
1
1
1
10
7
0
7
5
5
0
7
5
5
1
2
0
1
1,329
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/tests/base.py
djedi.tests.base.DjediTest
class DjediTest(TransactionTestCase): def setUp(self): from cio.backends import cache from cio.environment import env from cio.pipeline import pipeline from cio.plugins import plugins env.reset() cache.clear() pipeline.clear() plugins.load() def tearDown(self): shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) @contextmanager def settings(self, *args, **kwargs): with super().settings(*args, **kwargs): with cio_settings(): configure() yield
class DjediTest(TransactionTestCase): def setUp(self): pass def tearDown(self): pass @contextmanager def settings(self, *args, **kwargs): pass
5
0
6
0
5
0
1
0
1
1
0
5
3
0
3
3
21
3
18
9
9
0
17
8
9
1
1
2
3
1,330
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/rest/api.py
djedi.rest.api.EmbedApi
class EmbedApi(View): def get(self, request): if has_permission(request): return render_embed(request=request) else: # We used to `raise PermissionDenied` here (which might seem more # appropriate), but that has the annoying side effect of being # logged as an error in the browser dev tools, making people think # something is wrong. return HttpResponse(status=204)
class EmbedApi(View): def get(self, request): pass
2
0
9
0
5
4
2
0.67
1
0
0
0
1
0
1
1
10
0
6
2
4
4
5
2
3
2
1
1
2
1,331
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/south_migrations/0001_initial.py
djedi.south_migrations.0001_initial.Migration
class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Node' db.create_table( "djedi_node", ( ("id", self.gf("django.db.models.fields.AutoField")(primary_key=True)), ( "key", self.gf("django.db.models.fields.CharField")( max_length=255, db_index=True ), ), ("content", self.gf("django.db.models.fields.TextField")(blank=True)), ("plugin", self.gf("django.db.models.fields.CharField")(max_length=8)), ( "version", self.gf("django.db.models.fields.CharField")(max_length=255), ), ( "is_published", self.gf("django.db.models.fields.BooleanField")(default=False), ), ( "meta", self.gf("django.db.models.fields.TextField")(null=True, blank=True), ), ( "date_created", self.gf("django.db.models.fields.DateTimeField")( auto_now_add=True, blank=True ), ), ), ) db.send_create_signal("djedi", ["Node"]) def backwards(self, orm): # Deleting model 'Node' db.delete_table("djedi_node") models = { "djedi.node": { "Meta": {"object_name": "Node"}, "content": ("django.db.models.fields.TextField", [], {"blank": "True"}), "date_created": ( "django.db.models.fields.DateTimeField", [], {"auto_now_add": "True", "blank": "True"}, ), "id": ("django.db.models.fields.AutoField", [], {"primary_key": "True"}), "is_published": ( "django.db.models.fields.BooleanField", [], {"default": "False"}, ), "key": ( "django.db.models.fields.CharField", [], {"max_length": "255", "db_index": "True"}, ), "meta": ( "django.db.models.fields.TextField", [], {"null": "True", "blank": "True"}, ), "plugin": ("django.db.models.fields.CharField", [], {"max_length": "8"}), "version": ("django.db.models.fields.CharField", [], {"max_length": "255"}), } } complete_apps = ["djedi"]
class Migration(SchemaMigration): def forwards(self, orm): pass def backwards(self, orm): pass
3
0
19
0
18
1
1
0.03
1
0
0
0
2
0
2
2
72
3
67
5
64
2
8
5
5
1
1
0
2
1,332
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/tests/base.py
djedi.tests.base.UserMixin
class UserMixin: def create_djedi_master(self): user = User.objects.create_superuser("master", "[email protected]", "test") return user def create_djedi_apprentice(self): user = User.objects.create_user( "apprentice", email="[email protected]", password="test" ) group, _ = Group.objects.get_or_create(name="Djedi") user.is_staff = True user.groups.add(group) user.save() return user
class UserMixin: def create_djedi_master(self): pass def create_djedi_apprentice(self): pass
3
0
6
0
6
0
1
0
0
0
0
2
2
0
2
2
14
1
13
6
10
0
11
6
8
1
0
0
2
1,333
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/tests/test_cache.py
djedi.tests.test_cache.CacheTest
class CacheTest(DjediTest): def test_set(self): uri = "i18n://sv-se@page/title.txt#1" content = "Title" self.assertIsNone(cache.get(uri)) cache.set(uri, content) node = cache.get(uri) self.assertEqual(node["uri"], uri) self.assertEqual(node["content"], content) cache.delete(uri) self.assertIsNone(cache.get(uri))
class CacheTest(DjediTest): def test_set(self): pass
2
0
13
3
10
1
1
0.09
1
1
0
0
1
0
1
4
14
3
11
5
9
1
11
5
9
1
2
0
1
1,334
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/tests/test_rest.py
djedi.tests.test_rest.PermissionTest
class PermissionTest(DjediTest, UserMixin): def setUp(self): super().setUp() self.master = self.create_djedi_master() self.apprentice = self.create_djedi_apprentice() def test_permissions(self): client = Client() url = reverse("admin:djedi:api", args=["i18n://sv-se@page/title"]) response = client.get(url) self.assertEqual(response.status_code, 403) logged_in = client.login(username=self.master.username, password="test") self.assertTrue(logged_in) response = client.get(url) self.assertEqual(response.status_code, 404) client.logout() logged_in = client.login(username=self.apprentice.username, password="test") self.assertTrue(logged_in) response = client.get(url) self.assertEqual(response.status_code, 404)
class PermissionTest(DjediTest, UserMixin): def setUp(self): pass def test_permissions(self): pass
3
0
11
2
9
0
1
0
2
1
0
0
2
2
2
7
23
4
19
9
16
0
19
9
16
1
2
0
2
1,335
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/tests/test_rest.py
djedi.tests.test_rest.PrivateRestTest
class PrivateRestTest(ClientTest): def get_api_url(self, url_name, uri): return reverse("admin:djedi:" + url_name, args=[quote(quote(uri, ""), "")]) def get(self, url_name, uri): url = self.get_api_url(url_name, uri) return self.client.get(url) def post(self, url_name, uri, data): url = self.get_api_url(url_name, uri) return self.client.post(url, data) def put(self, url_name, uri, data=None): url = self.get_api_url(url_name, uri) return self.client.put(url, data=data or {}) def delete(self, url_name, uri): url = self.get_api_url(url_name, uri) return self.client.delete(url) def test_get(self): response = self.get("api", "i18n://sv-se@page/title") self.assertEqual(response.status_code, 404) cio.set("i18n://sv-se@page/title.md", "# Djedi", publish=False) response = self.get("api", "i18n://sv-se@page/title") self.assertEqual(response.status_code, 404) response = self.get("api", "i18n://sv-se@page/title#draft") self.assertEqual(response.status_code, 200) node = json_node(response) self.assertKeys(node, "uri", "content") self.assertEqual(node["uri"], "i18n://sv-se@page/title.md#draft") self.assertRenderedMarkdown(node["content"], "# Djedi") def test_load(self): response = self.get("api.load", "i18n://sv-se@page/title") self.assertEqual(response.status_code, 200) json_content = json.loads(response.content) self.assertEqual(json_content["uri"], "i18n://sv-se@page/title.txt") self.assertIsNone(json_content["data"]) self.assertEqual(len(json_content["meta"].keys()), 0) # TODO: Should get 404 # response = self.get('api.load', 'i18n://sv-se@page/title#1') # self.assertEqual(response.status_code, 404) cio.set("i18n://sv-se@page/title.md", "# Djedi") response = self.get("api.load", "sv-se@page/title") self.assertEqual(response.status_code, 200) node = json_node(response, simple=False) meta = node.pop("meta", {}) content = "# Djedi" if cio.PY26 else "<h1>Djedi</h1>" self.assertDictEqual( node, { "uri": "i18n://sv-se@page/title.md#1", "data": "# Djedi", "content": content, }, ) self.assertKeys(meta, "modified_at", "published_at", "is_published") response = self.get("api.load", "i18n://sv-se@page/title#1") json_content = json.loads(response.content) self.assertEqual(json_content["uri"], "i18n://sv-se@page/title.md#1") self.assertEqual(len(cio.revisions("i18n://sv-se@page/title")), 1) def test_set(self): response = self.post("api", "i18n://page/title", {"data": "# Djedi"}) self.assertEqual(response.status_code, 400) response = self.post( "api", "i18n://sv-se@page/title.txt", {"data": "# Djedi", "data[extra]": "foobar"}, ) self.assertEqual(response.status_code, 400) uri = "i18n://sv-se@page/title.md" response = self.post( "api", uri, {"data": "# Djedi", "meta[message]": "lundberg"} ) self.assertEqual(response.status_code, 200) node = json_node(response, simple=False) meta = node.pop("meta") content = "# Djedi" if cio.PY26 else "<h1>Djedi</h1>" self.assertDictEqual( node, {"uri": "i18n://sv-se@page/title.md#draft", "content": content} ) self.assertEqual(meta["author"], "master") self.assertEqual(meta["message"], "lundberg") node = cio.get(uri, lazy=False) self.assertIsNone(node.content) cio.publish(uri) node = cio.get(uri, lazy=False) self.assertEqual(node.uri, "i18n://sv-se@page/title.md#1") self.assertRenderedMarkdown(node.content, "# Djedi") response = self.post( "api", node.uri, {"data": "# Djedi", "meta[message]": "Lundberg"} ) node = json_node(response, simple=False) self.assertEqual(node["meta"]["message"], "Lundberg") with self.assertRaises(PersistenceError): storage.backend._create(URI(node["uri"]), None) def test_delete(self): response = self.delete("api", "i18n://sv-se@page/title") self.assertEqual(response.status_code, 404) node = cio.set("i18n://sv-se@page/title.md", "# Djedi") response = self.delete("api", node.uri) self.assertEqual(response.status_code, 200) self.assertEqual(smart_str(response.content), "") with self.assertRaises(NodeDoesNotExist): storage.get("i18n://sv-se@page/title") node = cio.get("i18n://page/title", lazy=False) self.assertIsNone(node.content) def test_publish(self): node = cio.set("sv-se@page/title", "Djedi", publish=False) response = self.get("api", "i18n://sv-se@page/title") self.assertEqual(response.status_code, 404) response = self.put("api.publish", node.uri) self.assertEqual(response.status_code, 200) response = self.get("api", "i18n://sv-se@page/title") self.assertEqual(response.status_code, 200) self.assertEqual( json_node(response), {"uri": "i18n://sv-se@page/title.txt#1", "content": "Djedi"}, ) response = self.put("api.publish", "i18n://sv-se@foo/bar.txt#draft") self.assertEqual(response.status_code, 404) def test_revisions(self): cio.set("sv-se@page/title", "Djedi 1") cio.set("sv-se@page/title", "Djedi 2") response = self.get("api.revisions", "sv-se@page/title") self.assertEqual(response.status_code, 200) content = json.loads(response.content) self.assertEqual( content, [ ["i18n://sv-se@page/title.txt#1", False], ["i18n://sv-se@page/title.txt#2", True], ], ) def test_render(self): response = self.post("api.render", "foo", {"data": "# Djedi"}) assert response.status_code == 404 response = self.post("api.render", "md", {"data": "# Djedi"}) assert response.status_code == 200 self.assertRenderedMarkdown(smart_str(response.content), "# Djedi") response = self.post( "api.render", "img", { "data": json.dumps( {"url": "/foo/bar.png", "width": "64", "height": "64"} ) }, ) self.assertEqual(response.status_code, 200) self.assertEqual( smart_str(response.content), '<img alt="" height="64" src="/foo/bar.png" width="64" />', ) def test_editor(self): response = self.get("cms.editor", "sv-se@page/title.foo") self.assertEqual(response.status_code, 404) response = self.get("cms.editor", "sv-se@page/title") self.assertEqual(response.status_code, 404) for ext in plugins: response = self.get("cms.editor", "sv-se@page/title." + ext) self.assertEqual(response.status_code, 200) if ext == "img": assert set(response.context_data.keys()) == { "THEME", "VERSION", "uri", "forms", } assert "HTML" in response.context_data["forms"] assert isinstance( response.context_data["forms"]["HTML"], BaseEditorForm ) self.assertListEqual( ["data__id", "data__alt", "data__class"], list(response.context_data["forms"]["HTML"].fields.keys()), ) else: assert set(response.context_data.keys()) == {"THEME", "VERSION", "uri"} self.assertNotIn(b"document.domain", response.content) with cio.conf.settings(XSS_DOMAIN="foobar.se"): response = self.post("cms.editor", "sv-se@page/title", {"data": "Djedi"}) self.assertEqual(response.status_code, 200) self.assertIn(b'document.domain = "foobar.se"', response.content) def test_image_dataform(self): from djedi.plugins.img import DataForm data_form = DataForm() html = data_form.as_table() self.assertTrue('name="data[alt]"' in html) self.assertTrue('name="data[class]"' in html) self.assertTrue('name="data[id]"' in html) def test_upload(self): tests_dir = os.path.dirname(os.path.abspath(__file__)) image_path = os.path.join(tests_dir, "assets", "image.png") form = { "data[width]": "64", "data[height]": "64", "data[crop]": "64,64,128,128", "data[id]": "vw", "data[class]": "year-53", "data[alt]": "Zwitter", "meta[comment]": "VW", } response = self.post("api", "i18n://sv-se@header/logo.img", form) self.assertEqual(response.status_code, 200) with open(image_path, "rb") as image: file = File(image, name=image_path) form["data[file]"] = file response = self.post("api", "i18n://sv-se@header/logo.img", form) self.assertEqual(response.status_code, 200) node = json_node(response, simple=False) meta = node.pop("meta") uri, content = node["uri"], node["content"] self.assertEqual(uri, "i18n://sv-se@header/logo.img#draft") self.assertEqual(meta["comment"], "VW") html = ( "<img " 'alt="Zwitter" ' 'class="year-53" ' 'height="64" ' 'id="vw" ' 'src="/media/djedi/img/03/5e/5eba6fc2149822a8dbf76cd6978798f2ddc4ac34.png" ' 'width="64" />' ) self.assertEqual(content, html) # Post new resized version node = cio.load(uri) del form["data[file]"] del form["data[crop]"] form["data[width]"] = form["data[height]"] = "32" form["data[filename]"] = node["data"]["filename"] response = self.post("api", "i18n://sv-se@header/logo.img", form) self.assertEqual(response.status_code, 200)
class PrivateRestTest(ClientTest): def get_api_url(self, url_name, uri): pass def get_api_url(self, url_name, uri): pass def post(self, url_name, uri, data): pass def put(self, url_name, uri, data=None): pass def delete(self, url_name, uri): pass def test_get(self): pass def test_load(self): pass def test_set(self): pass def test_delete(self): pass def test_publish(self): pass def test_revisions(self): pass def test_render(self): pass def test_editor(self): pass def test_image_dataform(self): pass def test_upload(self): pass
16
0
18
3
15
2
1
0.14
1
4
2
0
15
0
15
25
283
55
224
54
207
31
160
53
143
3
3
2
19
1,336
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/tests/test_settings.py
djedi.tests.test_settings.SettingsTest
class SettingsTest(DjediTest): def test_settings(self): self.assertEqual(settings.THEME, "luke") def test_plugin_settings(self): plugin = plugins.get("img") self.assertIn("foo", plugin.settings.keys()) def test_default_scheme(self): self.assertEqual(settings.URI_DEFAULT_SCHEME, "i18n") with self.settings(DJEDI={"URI_DEFAULT_SCHEME": "l10n"}): self.assertEqual(settings.URI_DEFAULT_SCHEME, "l10n") self.assertEqual(settings.URI_DEFAULT_SCHEME, "i18n")
class SettingsTest(DjediTest): def test_settings(self): pass def test_plugin_settings(self): pass def test_default_scheme(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
6
13
2
11
5
7
0
11
5
7
1
2
1
3
1,337
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/plugins/form.py
djedi.plugins.form.BaseEditorForm
class BaseEditorForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in list(self.fields.keys()): self.fields[field].widget.__class__ = get_custom_render_widget( self.fields[field].widget.__class__ )
class BaseEditorForm(forms.Form): def __init__(self, *args, **kwargs): pass
2
0
7
1
6
0
2
0
1
2
0
1
1
0
1
1
8
1
7
3
5
0
5
3
3
2
1
1
2
1,338
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/plugins/base.py
djedi.plugins.base.DjediPlugin
class DjediPlugin(BasePlugin): def get_editor_context(self, **kwargs): """ Returns custom context """ return kwargs
class DjediPlugin(BasePlugin): def get_editor_context(self, **kwargs): ''' Returns custom context ''' pass
2
1
5
0
2
3
1
1
1
0
0
1
1
0
1
1
6
0
3
2
1
3
3
2
1
1
1
0
1
1,339
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/tests/test_rest.py
djedi.tests.test_rest.PublicRestTest
class PublicRestTest(ClientTest): def test_api_root_not_found(self): url = reverse("admin:djedi:rest:api-base") response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_embed(self): url = reverse("admin:djedi:rest:embed") response = self.client.get(url) html = smart_str(response.content) self.assertIn('iframe id="djedi-cms"', html) cms_url = "http://testserver" + reverse("admin:djedi:cms") self.assertIn(cms_url, html) self.assertNotIn("window.DJEDI_NODES", html) self.assertNotIn("document.domain", html) with cio.conf.settings(XSS_DOMAIN="foobar.se"): response = self.client.get(url) self.assertIn(b'document.domain = "foobar.se"', response.content) self.client.logout() response = self.client.get(url) self.assertEqual(response.status_code, 204) def test_nodes(self): with self.assertCache(sets=1): cio.set("sv-se@rest/label/email", "E-post") with self.assertDB(calls=1), self.assertCache( calls=1, misses=1, hits=1, sets=0 ): url = reverse("admin:djedi:rest:nodes") response = self.client.post( url, json.dumps( { "rest/page/body.md": "# Foo Bar", "rest/label/email": "E-mail", } ), content_type="application/json", ) json_content = json.loads(response.content) self.assertIn("i18n://sv-se@rest/page/body.md", json_content.keys()) self.assertEqual( json_content["i18n://sv-se@rest/page/body.md"], "<h1>Foo Bar</h1>" ) self.assertIn("i18n://sv-se@rest/label/email.txt#1", json_content.keys()) self.assertEqual(json_content["i18n://sv-se@rest/label/email.txt#1"], "E-post")
class PublicRestTest(ClientTest): def test_api_root_not_found(self): pass def test_embed(self): pass def test_nodes(self): pass
4
0
16
2
14
1
1
0.07
1
1
0
0
3
0
3
13
52
8
44
13
40
3
31
13
27
1
3
1
3
1,340
5monkeys/djedi-cms
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_djedi-cms/djedi/admin/api.py
djedi.admin.api.APIView
class APIView(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): if not auth.has_permission(request): raise PermissionDenied try: return super().dispatch(request, *args, **kwargs) except Http404: raise except Exception as e: return HttpResponseBadRequest(e) def get_post_data(self, request): """ Collect and merge post parameters with multipart files. """ params = dict(request.POST) params.update(request.FILES) data = defaultdict(dict) # Split data and meta parameters for param in sorted(params.keys()): value = params[param] if isinstance(value, list) and len(value) <= 1: value = value[0] if value else None prefix, _, field = param.partition("[") if field: field = field[:-1] try: data[prefix][field] = value except TypeError: raise InvalidNodeData( 'Got both reserved parameter "data" and plugin specific parameters.' ) else: data[prefix] = value return data["data"], data["meta"] def decode_uri(self, uri): decoded = unquote(uri) # If uri got decoded then recursive try more times until nothing more can be decoded if decoded != uri: decoded = self.decode_uri(decoded) return decoded def render_to_response(self, content=""): return HttpResponse(content)
class APIView(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): pass def get_post_data(self, request): ''' Collect and merge post parameters with multipart files. ''' pass def decode_uri(self, uri): pass def render_to_response(self, content=""): pass
6
1
12
2
9
1
3
0.13
1
6
1
6
4
0
4
4
54
11
38
13
32
5
34
11
29
6
1
3
13
1,341
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/rest/api.py
djedi.rest.api.APIView
class APIView(JSONResponseMixin, View): @csrf_exempt def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs)
class APIView(JSONResponseMixin, View): @csrf_exempt def dispatch(self, request, *args, **kwargs): pass
3
0
2
0
2
0
1
0
2
1
0
1
1
0
1
3
4
0
4
3
1
0
3
2
1
1
1
0
1
1,342
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/plugins/img.py
djedi.plugins.img.ImagePlugin
class ImagePlugin(ImagePluginBase): """ Image plugin extending abstract content-io image plugin to use django file storage. """ @property def _file_storage(self): # Get configured file storage from settings file_storage = self.settings.get("FILE_STORAGE") # Fallback on default file storage if not file_storage: from django.core.files.storage import default_storage as file_storage return file_storage def _open(self, filename): return self._file_storage.open(filename) def _save(self, filename, bytes): content = InMemoryUploadedFile(bytes, None, filename, None, None, None) return self._file_storage.save(filename, content) def _url(self, filename): return self._file_storage.url(filename)
class ImagePlugin(ImagePluginBase): ''' Image plugin extending abstract content-io image plugin to use django file storage. ''' @property def _file_storage(self): pass def _open(self, filename): pass def _save(self, filename, bytes): pass def _url(self, filename): pass
6
1
4
1
3
1
1
0.36
1
0
0
0
4
0
4
18
25
6
14
9
7
5
13
8
7
2
4
1
5
1,343
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/migrations/0003_alter_node_id.py
djedi.migrations.0003_alter_node_id.Migration
class Migration(migrations.Migration): dependencies = [ ("djedi", "0002_auto_20190722_1447"), ] operations = [ migrations.AlterField( model_name="node", name="id", field=models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID" ), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
14
1
13
3
12
0
3
3
2
0
1
0
0
1,344
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/migrations/0002_auto_20190722_1447.py
djedi.migrations.0002_auto_20190722_1447.Migration
class Migration(migrations.Migration): dependencies = [ ("djedi", "0001_initial"), ] operations = [ migrations.AlterField( model_name="node", name="is_published", field=models.BooleanField(blank=True, default=False), ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
12
1
11
3
10
0
3
3
2
0
1
0
0
1,345
5monkeys/djedi-cms
5monkeys_djedi-cms/djedi/templatetags/djedi_tags.py
djedi.templatetags.djedi_tags.BlockNode
class BlockNode(template.Node): """ Block node tag using body content as default: {% blocknode 'page/title' edit=True %} Lorem ipsum {% endblocknode %} """ @classmethod def tag(cls, parser, token): # Parse tag args and kwargs bits = token.split_contents()[1:] params = ("uri", "edit") args, kwargs = parse_bits( parser=parser, bits=bits, params=params, varargs=None, varkw=True, defaults=(True,), kwonly=(), kwonly_defaults=(), takes_context=None, name="blocknode", ) # Assert uri is the only tag arg if len(args) > 1: raise TemplateSyntaxError("Malformed arguments to blocknode tag") # Resolve uri variable uri = args[0].resolve({}) # Parse tag body (default content) tokens = parser.parse(("endblocknode",)) parser.delete_first_token() # Remove endblocknode tag # Render default content tokens and dedent common leading whitespace default = "".join(token.render({}) for token in tokens) default = default.strip("\n\r") default = textwrap.dedent(default) # Get node for uri, lacks context variable lookup due to lazy loading. node = cio.get(uri, default) return cls(tokens, node, kwargs) def __init__(self, tokens, node, kwargs): self.tokens = tokens self.node = node self.kwargs = kwargs def render(self, context): # Resolve tag kwargs against context resolved_kwargs = { key: value.resolve(context) for key, value in self.kwargs.items() } edit = resolved_kwargs.pop("edit", True) return render_node(self.node, context=resolved_kwargs, edit=edit)
class BlockNode(template.Node): ''' Block node tag using body content as default: {% blocknode 'page/title' edit=True %} Lorem ipsum {% endblocknode %} ''' @classmethod def tag(cls, parser, token): pass def __init__(self, tokens, node, kwargs): pass def render(self, context): pass
5
1
16
2
12
3
1
0.38
1
0
0
0
2
3
3
3
60
10
37
17
32
14
23
16
19
2
1
1
4
1,346
6809/MC6809
6809_MC6809/MC6809/tests/test_6809_arithmetic_shift.py
MC6809.tests.test_6809_arithmetic_shift.Test6809_Rotate
class Test6809_Rotate(BaseCPUTestCase): """ unittests for: * ROL (Rotate Left) alias * ROR (Rotate Right) alias """ def assertROL(self, src, dst, source_carry): src_bit_str = f'{src:08b}' dst_bit_str = f'{dst:08b}' print(f"{src:02x} {src_bit_str} > ROLA > {dst:02x} {dst_bit_str} -> {self.cpu.get_cc_info()}") # Carry was cleared and moved into bit 0 excpeted_bits = f"{src_bit_str[1:]}{source_carry}" self.assertEqual(dst_bit_str, excpeted_bits) # test negative if dst >= 0x80: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if dst == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow source_bit6 = is_bit_set(src, bit=6) source_bit7 = is_bit_set(src, bit=7) if source_bit6 == source_bit7: # V = bit 6 XOR bit 7 self.assertEqual(self.cpu.V, 0) else: self.assertEqual(self.cpu.V, 1) # test carry if 0x80 <= src <= 0xff: # if bit 7 was set self.assertEqual(self.cpu.C, 1) else: self.assertEqual(self.cpu.C, 0) def test_ROLA_with_clear_carry(self): for a in range(0x100): self.cpu.set_cc(0x00) # clear all CC flags self.cpu.accu_a.set(a) a = self.cpu.accu_a.value self.cpu_test_run(start=0x0000, end=None, mem=[ 0x49, # ROLA ]) r = self.cpu.accu_a.value self.assertROL(a, r, source_carry=0) # test half carry is uneffected! self.assertEqual(self.cpu.H, 0) def test_ROLA_with_set_carry(self): for a in range(0x100): self.cpu.set_cc(0xff) # set all CC flags self.cpu.accu_a.set(a) a = self.cpu.accu_a.value self.cpu_test_run(start=0x0000, end=None, mem=[ 0x49, # ROLA ]) r = self.cpu.accu_a.value self.assertROL(a, r, source_carry=1) # test half carry is uneffected! self.assertEqual(self.cpu.H, 1) def test_ROL_memory_with_clear_carry(self): for a in range(0x100): self.cpu.set_cc(0x00) # clear all CC flags self.cpu.memory.write_byte(0x0050, a) self.cpu_test_run(start=0x0000, end=None, mem=[ 0x09, 0x50, # ROL #$50 ]) r = self.cpu.memory.read_byte(0x0050) self.assertROL(a, r, source_carry=0) # test half carry is uneffected! self.assertEqual(self.cpu.H, 0) def test_ROL_memory_with_set_carry(self): for a in range(0x100): self.cpu.set_cc(0xff) # set all CC flags self.cpu.memory.write_byte(0x0050, a) self.cpu_test_run(start=0x0000, end=None, mem=[ 0x09, 0x50, # ROL #$50 ]) r = self.cpu.memory.read_byte(0x0050) self.assertROL(a, r, source_carry=1) # test half carry is uneffected! self.assertEqual(self.cpu.H, 1) def assertROR(self, src, dst, source_carry): src_bit_str = f'{src:08b}' dst_bit_str = f'{dst:08b}' # print "%02x %s > RORA > %02x %s -> %s" % ( # src, src_bit_str, # dst, dst_bit_str, # self.cpu.get_cc_info() # ) # Carry was cleared and moved into bit 0 excpeted_bits = f"{source_carry}{src_bit_str[:-1]}" self.assertEqual(dst_bit_str, excpeted_bits) # test negative if dst >= 0x80: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if dst == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test carry source_bit0 = is_bit_set(src, bit=0) if source_bit0: # if bit 0 was set self.assertEqual(self.cpu.C, 1) else: self.assertEqual(self.cpu.C, 0) def test_RORA_with_clear_carry(self): for a in range(0x100): self.cpu.set_cc(0x00) # clear all CC flags self.cpu.accu_a.set(a) a = self.cpu.accu_a.value self.cpu_test_run(start=0x0000, end=None, mem=[ 0x46, # RORA ]) r = self.cpu.accu_a.value self.assertROR(a, r, source_carry=0) # test half carry and overflow, they are uneffected! self.assertEqual(self.cpu.H, 0) self.assertEqual(self.cpu.V, 0) def test_RORA_with_set_carry(self): for a in range(0x100): self.cpu.set_cc(0xff) # set all CC flags self.cpu.accu_a.set(a) a = self.cpu.accu_a.value self.cpu_test_run(start=0x0000, end=None, mem=[ 0x46, # RORA ]) r = self.cpu.accu_a.value self.assertROR(a, r, source_carry=1) # test half carry and overflow, they are uneffected! self.assertEqual(self.cpu.H, 1) self.assertEqual(self.cpu.V, 1) def test_ROR_memory_with_clear_carry(self): for a in range(0x100): self.cpu.set_cc(0x00) # clear all CC flags self.cpu.memory.write_byte(0x0050, a) self.cpu_test_run(start=0x0000, end=None, mem=[ 0x06, 0x50, # ROR #$50 ]) r = self.cpu.memory.read_byte(0x0050) self.assertROR(a, r, source_carry=0) # test half carry and overflow, they are uneffected! self.assertEqual(self.cpu.H, 0) self.assertEqual(self.cpu.V, 0) def test_ROR_memory_with_set_carry(self): for a in range(0x100): self.cpu.set_cc(0xff) # set all CC flags self.cpu.memory.write_byte(0x0050, a) self.cpu_test_run(start=0x0000, end=None, mem=[ 0x06, 0x50, # ROR #$50 ]) r = self.cpu.memory.read_byte(0x0050) self.assertROR(a, r, source_carry=1) # test half carry and overflow, they are uneffected! self.assertEqual(self.cpu.H, 1) self.assertEqual(self.cpu.V, 1)
class Test6809_Rotate(BaseCPUTestCase): ''' unittests for: * ROL (Rotate Left) alias * ROR (Rotate Right) alias ''' def assertROL(self, src, dst, source_carry): pass def test_ROLA_with_clear_carry(self): pass def test_ROLA_with_set_carry(self): pass def test_ROL_memory_with_clear_carry(self): pass def test_ROL_memory_with_set_carry(self): pass def assertROR(self, src, dst, source_carry): pass def test_RORA_with_clear_carry(self): pass def test_RORA_with_set_carry(self): pass def test_ROR_memory_with_clear_carry(self): pass def test_ROR_memory_with_set_carry(self): pass
11
1
17
2
13
4
3
0.35
1
1
0
0
10
0
10
93
185
27
131
36
120
46
108
36
97
5
4
1
25
1,347
6809/MC6809
6809_MC6809/MC6809/tests/test_6809_arithmetic_shift.py
MC6809.tests.test_6809_arithmetic_shift.Test6809_LogicalShift
class Test6809_LogicalShift(BaseCPUTestCase): """ unittests for: * LSL (Logical Shift Left) alias ASL (Arithmetic Shift Left) * LSR (Logical Shift Right) alias ASR (Arithmetic Shift Right) """ def test_LSRA_inherent(self): """ Example assembler code to test LSRA/ASRA CLRB ; B is always 0 TFR B,U ; clear U loop: TFR U,A ; for next test TFR B,CC ; clear CC LSRA NOP LEAU 1,U ; inc U JMP loop """ for i in range(0x100): self.cpu.accu_a.set(i) self.cpu.set_cc(0x00) # Clear all CC flags self.cpu_test_run(start=0x1000, end=None, mem=[ 0x44, # LSRA/ASRA Inherent ]) r = self.cpu.accu_a.value # print "%02x %s > ASRA > %02x %s -> %s" % ( # i, '{0:08b}'.format(i), # r, '{0:08b}'.format(r), # self.cpu.get_cc_info() # ) # test LSL result r2 = i >> 1 # shift right r2 = r2 & 0xff # wrap around self.assertEqualHex(r, r2) # test negative if 128 <= r <= 255: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if r == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow self.assertEqual(self.cpu.V, 0) # test carry source_bit0 = get_bit(i, bit=0) self.assertEqual(self.cpu.C, source_bit0) def test_LSLA_inherent(self): for i in range(260): self.cpu.accu_a.set(i) self.cpu.set_cc(0x00) # Clear all CC flags self.cpu_test_run(start=0x1000, end=None, mem=[ 0x48, # LSLA/ASLA Inherent ]) r = self.cpu.accu_a.value # print "%02x %s > LSLA > %02x %s -> %s" % ( # i, '{0:08b}'.format(i), # r, '{0:08b}'.format(r), # self.cpu.get_cc_info() # ) # test LSL result r2 = i << 1 # shift left r2 = r2 & 0xff # wrap around self.assertEqualHex(r, r2) # test negative if 128 <= r <= 255: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if r == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow if 64 <= i <= 191: self.assertEqual(self.cpu.V, 1) else: self.assertEqual(self.cpu.V, 0) # test carry if 128 <= i <= 255: self.assertEqual(self.cpu.C, 1) else: self.assertEqual(self.cpu.C, 0) def test_ASR_inherent(self): """ Shifts all bits of the operand one place to the right. Bit seven is held constant. Bit zero is shifted into the C (carry) bit. """ for src in range(0x100): self.cpu.accu_b.set(src) self.cpu.set_cc(0x00) # Set all CC flags self.cpu_test_run(start=0x1000, end=None, mem=[ 0x57, # ASRB/LSRB Inherent ]) dst = self.cpu.accu_b.value src_bit_str = f'{src:08b}' dst_bit_str = f'{dst:08b}' # print "%02x %s > ASRB > %02x %s -> %s" % ( # src, src_bit_str, # dst, dst_bit_str, # self.cpu.get_cc_info() # ) # Bit seven is held constant. if src_bit_str[0] == "1": excpeted_bits = f"1{src_bit_str[:-1]}" else: excpeted_bits = f"0{src_bit_str[:-1]}" # test ASRB/LSRB result self.assertEqual(dst_bit_str, excpeted_bits) # test negative if 128 <= dst <= 255: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if dst == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow (is uneffected!) self.assertEqual(self.cpu.V, 0) # test carry source_bit0 = is_bit_set(src, bit=0) if source_bit0: self.assertEqual(self.cpu.C, 1) else: self.assertEqual(self.cpu.C, 0)
class Test6809_LogicalShift(BaseCPUTestCase): ''' unittests for: * LSL (Logical Shift Left) alias ASL (Arithmetic Shift Left) * LSR (Logical Shift Right) alias ASR (Arithmetic Shift Right) ''' def test_LSRA_inherent(self): ''' Example assembler code to test LSRA/ASRA CLRB ; B is always 0 TFR B,U ; clear U loop: TFR U,A ; for next test TFR B,CC ; clear CC LSRA NOP LEAU 1,U ; inc U JMP loop ''' pass def test_LSLA_inherent(self): pass def test_ASR_inherent(self): ''' Shifts all bits of the operand one place to the right. Bit seven is held constant. Bit zero is shifted into the C (carry) bit. ''' pass
4
3
48
6
26
19
5
0.78
1
1
0
0
3
0
3
86
153
22
79
17
75
62
63
17
59
6
4
2
16
1,348
6809/MC6809
6809_MC6809/MC6809/tests/test_6809_StoreLoad.py
MC6809.tests.test_6809_StoreLoad.Test6809_Store
class Test6809_Store(BaseStackTestCase): def test_STA_direct(self): self.cpu.direct_page.set(0x41) self.cpu.accu_a.set(0xad) self.cpu_test_run(start=0x4000, end=None, mem=[0x97, 0xfe]) # STA <$fe (Direct) self.assertEqualHex(self.cpu.memory.read_byte(0x41fe), 0xad) def test_STB_extended(self): self.cpu.accu_b.set(0x81) self.cpu_test_run(start=0x4000, end=None, mem=[0xF7, 0x50, 0x10]) # STB $5010 (Extended) self.assertEqualHex(self.cpu.memory.read_byte(0x5010), 0x81) def test_STD_extended(self): self.cpu.accu_d.set(0x4321) self.cpu_test_run(start=0x4000, end=None, mem=[0xFD, 0x50, 0x01]) # STD $5001 (Extended) self.assertEqualHex(self.cpu.memory.read_word(0x5001), 0x4321) def test_STS_indexed(self): self.cpu.system_stack_pointer.set(0x1234) self.cpu.index_x.set(0x0218) self.cpu_test_run(start=0x1b5c, end=None, mem=[0x10, 0xef, 0x83]) # STS ,R-- (indexed) self.assertEqualHex(self.cpu.memory.read_word(0x0216), 0x1234)
class Test6809_Store(BaseStackTestCase): def test_STA_direct(self): pass def test_STB_extended(self): pass def test_STD_extended(self): pass def test_STS_indexed(self): pass
5
0
5
0
5
1
1
0.26
1
0
0
0
4
0
4
88
22
3
19
5
14
5
19
5
14
1
5
0
4
1,349
6809/MC6809
6809_MC6809/MC6809/tests/test_6809_arithmetic.py
MC6809.tests.test_6809_arithmetic.Test6809_Arithmetic
class Test6809_Arithmetic(BaseCPUTestCase): def test_ADDA_extended01(self): self.cpu_test_run(start=0x1000, end=0x1003, mem=[ 0xbb, # ADDA extended 0x12, 0x34 # word to add on accu A ]) self.assertEqual(self.cpu.Z, 1) self.assertEqual(self.cpu.get_cc_value(), 0x04) self.assertEqual(self.cpu.accu_a.value, 0x00) def test_ADDA_immediate(self): # expected values are: 1 up to 255 then wrap around to 0 and up to 4 excpected_values = list(range(1, 256)) excpected_values += list(range(0, 5)) self.cpu.accu_a.set(0x00) # start value for i in range(260): self.cpu.set_cc(0x00) # Clear all CC flags self.cpu_test_run(start=0x1000, end=None, mem=[ 0x8B, 0x01, # ADDA #$1 Immediate ]) a = self.cpu.accu_a.value excpected_value = excpected_values[i] # print i, a, excpected_value, self.cpu.get_cc_info() # test ADDA result self.assertEqual(a, excpected_value) # test half carry if a % 16 == 0: self.assertEqual(self.cpu.H, 1) else: self.assertEqual(self.cpu.H, 0) # test negative if 128 <= a <= 255: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if a == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow if a == 128: self.assertEqual(self.cpu.V, 1) else: self.assertEqual(self.cpu.V, 0) # test carry if a == 0: self.assertEqual(self.cpu.C, 1) else: self.assertEqual(self.cpu.C, 0) def test_ADDA1(self): for i in range(260): self.cpu_test_run(start=0x1000, end=None, mem=[ 0x8B, 0x01, # ADDA #$01 ]) r = self.cpu.accu_a.value # print "$%02x > ADD 1 > $%02x | CC:%s" % ( # i, r, self.cpu.get_cc_info() # ) # test INC value from RAM self.assertEqualHex(i + 1 & 0xff, r) # expected values are: 1 up to 255 then wrap around to 0 and up to 4 # test negative if 128 <= r <= 255: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if r == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow if r == 0x80: self.assertEqual(self.cpu.V, 1) else: self.assertEqual(self.cpu.V, 0) def test_ADDD1(self): areas = list(range(0, 3)) + ["..."] + list(range(0x7ffd, 0x8002)) + ["..."] + list(range(0xfffd, 0x10002)) for i in areas: if i == "...": # print "..." continue self.cpu.accu_d.set(i) self.cpu_test_run(start=0x1000, end=None, mem=[ 0xc3, 0x00, 0x01, # ADDD #$01 ]) r = self.cpu.accu_d.value # print "%5s $%04x > ADDD 1 > $%04x | CC:%s" % ( # i, i, r, self.cpu.get_cc_info() # ) # test INC value from RAM self.assertEqualHex(i + 1 & 0xffff, r) # test negative if 0x8000 <= r <= 0xffff: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if r == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow if r == 0x8000: self.assertEqual(self.cpu.V, 1) else: self.assertEqual(self.cpu.V, 0) def test_NEGA(self): """ Example assembler code to test NEGA CLRB ; B is always 0 TFR B,U ; clear U loop: TFR U,A ; for next NEGA TFR B,CC ; clear CC NEGA LEAU 1,U ; inc U JMP loop 0000 5F CLRB ; B is always 0 0001 1F 93 TFR B,U ; clear U 0003 LOOP: 0003 1F 38 TFR U,A ; for next NEGA 0005 1F 9A TFR B,CC ; clear CC 0007 40 NEGA 0008 33 41 LEAU 1,U ; inc U 000A 0E 03 JMP loop """ excpected_values = [0] + list(range(255, 0, -1)) for a in range(256): self.cpu.set_cc(0x00) self.cpu_test_run(start=0x1000, end=None, mem=[ 0x86, a, # LDA #$i 0x40, # NEGA (inherent) ]) r = self.cpu.accu_a.value # print "%03s - a=%02x r=%02x -> %s" % ( # a, a, r, self.cpu.get_cc_info() # ) excpected_value = excpected_values[a] """ xroar NEG CC - input for NEG values: H = uneffected N = dez: 1-128 | hex: $01 - $80 Z = dez: 0 | hex: $00 V = dez: 128 | hex: $80 C = dez: 1-255 | hex: $01 - $ff """ # test NEG result self.assertEqual(r, excpected_value) # test half carry is uneffected! self.assertEqual(self.cpu.H, 0) # test negative: 0x01 <= a <= 0x80 if 1 <= a <= 128: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero | a==0 and r==0 if r == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow | a==128 and r==128 if r == 128: self.assertEqual(self.cpu.V, 1) else: self.assertEqual(self.cpu.V, 0) # test carry is set if r=1-255 (hex: r=$01 - $ff) if r >= 1: self.assertEqual(self.cpu.C, 1) else: self.assertEqual(self.cpu.C, 0) def test_NEG_memory(self): excpected_values = [0] + list(range(255, 0, -1)) address = 0x10 for a in range(256): self.cpu.set_cc(0x00) self.cpu.memory.write_byte(address, a) self.cpu_test_run(start=0x0000, end=None, mem=[ 0x00, address, # NEG address ]) r = self.cpu.memory.read_byte(address) # print "%03s - a=%02x r=%02x -> %s" % ( # a, a, r, self.cpu.get_cc_info() # ) excpected_value = excpected_values[a] # test NEG result self.assertEqual(r, excpected_value) # test half carry is uneffected! self.assertEqual(self.cpu.H, 0) # test negative: 0x01 <= a <= 0x80 if 1 <= a <= 128: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero | a==0 and r==0 if r == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow | a==128 and r==128 if r == 128: self.assertEqual(self.cpu.V, 1) else: self.assertEqual(self.cpu.V, 0) # test carry is set if r=1-255 (hex: r=$01 - $ff) if r >= 1: self.assertEqual(self.cpu.C, 1) else: self.assertEqual(self.cpu.C, 0) def test_INC_memory(self): # expected values are: 1 up to 255 then wrap around to 0 and up to 4 excpected_values = list(range(1, 256)) excpected_values += list(range(0, 5)) self.cpu.memory.write_byte(0x4500, 0x0) # start value for i in range(260): self.cpu.set_cc(0x00) # Clear all CC flags self.cpu_test_run(start=0x1000, end=None, mem=[ 0x7c, 0x45, 0x00, # INC $4500 ]) r = self.cpu.memory.read_byte(0x4500) excpected_value = excpected_values[i] # print "%5s $%02x > INC > $%02x | CC:%s" % ( # i, i, r, self.cpu.get_cc_info() # ) # test INC value from RAM self.assertEqualHex(r, excpected_value) self.assertEqualHex(i + 1 & 0xff, r) # test negative if 128 <= r <= 255: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if r == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow if r == 0x80: self.assertEqual(self.cpu.V, 1) else: self.assertEqual(self.cpu.V, 0) def test_INCB(self): # expected values are: 1 up to 255 then wrap around to 0 and up to 4 excpected_values = list(range(1, 256)) excpected_values += list(range(0, 5)) for i in range(260): self.cpu_test_run(start=0x1000, end=None, mem=[ 0x5c, # INCB ]) r = self.cpu.accu_b.value excpected_value = excpected_values[i] # print "%5s $%02x > INC > $%02x | CC:%s" % ( # i, i, r, self.cpu.get_cc_info() # ) # test INC value from RAM self.assertEqual(r, excpected_value) self.assertEqualHex(i + 1 & 0xff, r) # test negative if 128 <= r <= 255: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if r == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow if r == 0x80: self.assertEqual(self.cpu.V, 1) else: self.assertEqual(self.cpu.V, 0) def test_INC_not_affected_flags1(self): self.cpu.memory.write_byte(0x0100, 0x00) # start value self.cpu.set_cc(0x00) # Clear all CC flags self.cpu_test_run(start=0x0000, end=None, mem=[ 0x7c, 0x01, 0x00, # INC $0100 ]) r = self.cpu.memory.read_byte(0x0100) self.assertEqual(r, 0x01) # half carry bit is not affected in INC self.assertEqual(self.cpu.H, 0) # carry bit is not affected in INC self.assertEqual(self.cpu.C, 0) def test_INC_not_affected_flags2(self): self.cpu.memory.write_byte(0x0100, 0x00) # start value self.cpu.set_cc(0xff) # Set all CC flags self.cpu_test_run(start=0x0000, end=None, mem=[ 0x7c, 0x01, 0x00, # INC $0100 ]) r = self.cpu.memory.read_byte(0x0100) self.assertEqual(r, 0x01) # half carry bit is not affected in INC self.assertEqual(self.cpu.H, 1) # carry bit is not affected in INC self.assertEqual(self.cpu.C, 1) def test_SUBA_immediate(self): # expected values are: 254 down to 0 than wrap around to 255 and down to 252 excpected_values = list(range(254, -1, -1)) excpected_values += list(range(255, 250, -1)) self.cpu.accu_a.set(0xff) # start value for i in range(260): self.cpu.set_cc(0x00) # Clear all CC flags self.cpu_test_run(start=0x1000, end=None, mem=[ 0x80, 0x01, # SUBA #$01 ]) a = self.cpu.accu_a.value excpected_value = excpected_values[i] # print i, a, excpected_value, self.cpu.get_cc_info() # test SUBA result self.assertEqual(a, excpected_value) # test half carry # XXX: half carry is "undefined" in SUBA! self.assertEqual(self.cpu.H, 0) # test negative if 128 <= a <= 255: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if a == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow if a == 127: # V ist set if SUB $80 to $7f self.assertEqual(self.cpu.V, 1) else: self.assertEqual(self.cpu.V, 0) # test carry if a == 0xff: # C is set if SUB $00 to $ff self.assertEqual(self.cpu.C, 1) else: self.assertEqual(self.cpu.C, 0) def test_SUBA_indexed(self): self.cpu.memory.load(0x1234, [0x12, 0xff]) self.cpu.system_stack_pointer.set(0x1234) self.cpu.accu_a.set(0xff) # start value self.cpu_test_run(start=0x1000, end=None, mem=[ 0xa0, 0xe0, # SUBA ,S+ ]) self.assertEqualHexByte(self.cpu.accu_a.value, 0xed) # $ff - $12 = $ed self.assertEqualHexWord(self.cpu.system_stack_pointer.value, 0x1235) self.cpu_test_run(start=0x1000, end=None, mem=[ 0xa0, 0xe0, # SUBA ,S+ ]) self.assertEqualHexByte(self.cpu.accu_a.value, 0xed - 0xff & 0xff) # $ee self.assertEqualHexWord(self.cpu.system_stack_pointer.value, 0x1236) def test_DEC_extended(self): # expected values are: 254 down to 0 than wrap around to 255 and down to 252 excpected_values = list(range(254, -1, -1)) excpected_values += list(range(255, 250, -1)) self.cpu.memory.write_byte(0x4500, 0xff) # start value self.cpu.accu_a.set(0xff) # start value for i in range(260): self.cpu.set_cc(0x00) # Clear all CC flags self.cpu_test_run(start=0x1000, end=None, mem=[ 0x7A, 0x45, 0x00, # DEC $4500 ]) r = self.cpu.memory.read_byte(0x4500) excpected_value = excpected_values[i] # print i, r, excpected_value, self.cpu.get_cc_info() # test DEC result self.assertEqual(r, excpected_value) # half carry bit is not affected in DEC self.assertEqual(self.cpu.H, 0) # test negative if 128 <= r <= 255: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if r == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow if r == 127: # V is set if SUB $80 to $7f self.assertEqual(self.cpu.V, 1) else: self.assertEqual(self.cpu.V, 0) # carry bit is not affected in DEC self.assertEqual(self.cpu.C, 0) def test_DECA(self): for a in range(256): self.cpu.set_cc(0x00) self.cpu.accu_a.set(a) self.cpu_test_run(start=0x1000, end=None, mem=[ 0x4a, # DECA ]) r = self.cpu.accu_a.value # print "%03s - %02x > DEC > %02x | CC:%s" % ( # a, a, r, self.cpu.get_cc_info() # ) # continue excpected_value = a - 1 & 0xff # test result self.assertEqual(r, excpected_value) # test half carry and carry is uneffected! self.assertEqual(self.cpu.H, 0) self.assertEqual(self.cpu.C, 0) # test negative: if r >= 0x80: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if r == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # test overflow if a == 0x80: self.assertEqual(self.cpu.V, 1) else: self.assertEqual(self.cpu.V, 0) def test_SBCA_immediate_01(self): a = 0x80 self.cpu.set_cc(0x00) # CC:........ self.cpu.accu_a.set(a) self.cpu_test_run(start=0x1000, end=None, mem=[ 0x82, 0x40, # SBC ]) r = self.cpu.accu_a.value # print "%02x > SBC > %02x | CC:%s" % ( # a, r, self.cpu.get_cc_info() # ) self.assertEqualHex(r, 0x80 - 0x40 - 0x00) self.assertEqual(self.cpu.get_cc_info(), "......V.") def test_SBCA_immediate_02(self): a = 0x40 self.cpu.set_cc(0xff) # CC:EFHINZVC self.cpu.accu_a.set(a) self.cpu_test_run(start=0x1000, end=None, mem=[ 0x82, 0x20, # SBC ]) r = self.cpu.accu_a.value # print "%02x > SBC > %02x | CC:%s" % ( # a, r, self.cpu.get_cc_info() # ) self.assertEqualHex(r, 0x40 - 0x20 - 0x01) # half-carry is undefined self.assertEqual(self.cpu.get_cc_info(), "EFHI....") def test_ORCC(self): a_areas = list(range(0, 3)) + ["..."] + list(range(0x7e, 0x83)) + ["..."] + list(range(0xfd, 0x100)) b_areas = list(range(0, 3)) + ["..."] + list(range(0x7e, 0x83)) + ["..."] + list(range(0xfd, 0x100)) for a in a_areas: if a == "...": # print "..." continue for b in b_areas: if b == "...": # print "..." continue self.cpu.set_cc(a) self.cpu_test_run(start=0x1000, end=None, mem=[ 0x1a, b # ORCC $a ]) r = self.cpu.get_cc_value() expected_value = a | b # print "%02x OR %02x = %02x | CC:%s" % ( # a, b, r, self.cpu.get_cc_info() # ) self.assertEqualHex(r, expected_value) def test_ANDCC(self): a_areas = list(range(0, 3)) + ["..."] + list(range(0x7e, 0x83)) + ["..."] + list(range(0xfd, 0x100)) b_areas = list(range(0, 3)) + ["..."] + list(range(0x7e, 0x83)) + ["..."] + list(range(0xfd, 0x100)) for a in a_areas: if a == "...": # print "..." continue for b in b_areas: if b == "...": # print "..." continue self.cpu.set_cc(a) self.cpu_test_run(start=0x1000, end=None, mem=[ 0x1c, b # ANDCC $a ]) r = self.cpu.get_cc_value() expected_value = a & b # print "%02x AND %02x = %02x | CC:%s" % ( # a, b, r, self.cpu.get_cc_info() # ) self.assertEqualHex(r, expected_value) def test_ABX(self): self.cpu.set_cc(0xff) x_areas = list(range(0, 3)) + ["..."] + list(range(0x7ffd, 0x8002)) + ["..."] + list(range(0xfffd, 0x10000)) b_areas = list(range(0, 3)) + ["..."] + list(range(0x7e, 0x83)) + ["..."] + list(range(0xfd, 0x100)) for x in x_areas: if x == "...": # print "..." continue for b in b_areas: if b == "...": # print "..." continue self.cpu.index_x.set(x) self.cpu.accu_b.set(b) self.cpu_test_run(start=0x1000, end=None, mem=[ 0x3a, # ABX (inherent) ]) r = self.cpu.index_x.value expected_value = x + b & 0xffff # print "%04x + %02x = %04x | CC:%s" % ( # x, b, r, self.cpu.get_cc_info() # ) self.assertEqualHex(r, expected_value) # CC complet uneffected: self.assertEqualHex(self.cpu.get_cc_value(), 0xff) def test_XOR(self): print("TODO!!!") # def setUp(self): # cmd_args = UnittestCmdArgs # cmd_args.trace = True # enable Trace output # cfg = TestCfg(cmd_args) # self.cpu = CPU(cfg) # self.cpu.set_cc(0x00) def test_DAA(self): self.cpu_test_run(start=0x0100, end=None, mem=[ 0x86, 0x67, # LDA #$67 ; A=$67 0x8b, 0x75, # ADDA #$75 ; A=$67+$75 = $DC 0x19, # DAA 19 ; A=67+75=142 -> $42 ]) self.assertEqualHexByte(self.cpu.accu_a.value, 0x42) self.assertEqual(self.cpu.C, 1) def test_DAA2(self): for add in range(0xff): self.cpu.set_cc(0x00) self.cpu.accu_a.set(0x01) self.cpu_test_run(start=0x0100, end=None, mem=[ 0x8b, add, # ADDA #$1 0x19, # DAA ]) r = self.cpu.accu_a.value # print "$01 + $%02x = $%02x > DAA > $%02x | CC:%s" % ( # add, (1 + add), r, self.cpu.get_cc_info() # ) # test half carry if add & 0x0f == 0x0f: self.assertEqual(self.cpu.H, 1) else: self.assertEqual(self.cpu.H, 0) # test negative if 128 <= r <= 255: self.assertEqual(self.cpu.N, 1) else: self.assertEqual(self.cpu.N, 0) # test zero if r == 0: self.assertEqual(self.cpu.Z, 1) else: self.assertEqual(self.cpu.Z, 0) # is undefined? # http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4896 # # test overflow # if r == 128: # self.assertEqual(self.cpu.V, 1) # else: # self.assertEqual(self.cpu.V, 0) # test carry if add >= 0x99: self.assertEqual(self.cpu.C, 1) else: self.assertEqual(self.cpu.C, 0)
class Test6809_Arithmetic(BaseCPUTestCase): def test_ADDA_extended01(self): pass def test_ADDA_immediate(self): pass def test_ADDA1(self): pass def test_ADDD1(self): pass def test_NEGA(self): ''' Example assembler code to test NEGA CLRB ; B is always 0 TFR B,U ; clear U loop: TFR U,A ; for next NEGA TFR B,CC ; clear CC NEGA LEAU 1,U ; inc U JMP loop 0000 5F CLRB ; B is always 0 0001 1F 93 TFR B,U ; clear U 0003 LOOP: 0003 1F 38 TFR U,A ; for next NEGA 0005 1F 9A TFR B,CC ; clear CC 0007 40 NEGA 0008 33 41 LEAU 1,U ; inc U 000A 0E 03 JMP loop ''' pass def test_NEG_memory(self): pass def test_INC_memory(self): pass def test_INCB(self): pass def test_INC_not_affected_flags1(self): pass def test_INC_not_affected_flags2(self): pass def test_SUBA_immediate(self): pass def test_SUBA_indexed(self): pass def test_DEC_extended(self): pass def test_DECA(self): pass def test_SBCA_immediate_01(self): pass def test_SBCA_immediate_02(self): pass def test_ORCC(self): pass def test_ANDCC(self): pass def test_ABX(self): pass def test_XOR(self): pass def test_DAA(self): pass def test_DAA2(self): pass
23
1
29
4
19
9
4
0.5
1
2
0
0
22
0
22
105
670
105
408
86
385
206
320
86
297
7
4
3
85
1,350
6809/MC6809
6809_MC6809/MC6809/tests/test_6809_branch_instructions.py
MC6809.tests.test_6809_branch_instructions.Test6809_BranchInstructions
class Test6809_BranchInstructions(BaseCPUTestCase): """ Test branch instructions """ def test_BCC_no(self): self.cpu.C = 1 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x24, 0xf4, # BCC -12 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x1002) def test_BCC_yes(self): self.cpu.C = 0 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x24, 0xf4, # BCC -12 ; ea = $1002 + -12 = $ff6 ]) self.assertEqualHex(self.cpu.program_counter.value, 0xff6) def test_LBCC_no(self): self.cpu.C = 1 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x24, 0x07, 0xe4, # LBCC +2020 ; ea = $1004 + 2020 = $17e8 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x1004) def test_LBCC_yes(self): self.cpu.C = 0 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x24, 0x07, 0xe4, # LBCC +2020 ; ea = $1004 + 2020 = $17e8 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x17e8) def test_BCS_no(self): self.cpu.C = 0 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x25, 0xf4, # BCS -12 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x1002) def test_BCS_yes(self): self.cpu.C = 1 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x25, 0xf4, # BCS -12 ; ea = $1002 + -12 = $ff6 ]) self.assertEqualHex(self.cpu.program_counter.value, 0xff6) def test_LBCS_no(self): self.cpu.C = 0 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x25, 0x07, 0xe4, # LBCS +2020 ; ea = $1004 + 2020 = $17e8 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x1004) def test_LBCS_yes(self): self.cpu.C = 1 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x25, 0x07, 0xe4, # LBCS +2020 ; ea = $1004 + 2020 = $17e8 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x17e8) def test_BEQ_no(self): self.cpu.Z = 0 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x27, 0xf4, # BEQ -12 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x1002) def test_BEQ_yes(self): self.cpu.Z = 1 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x27, 0xf4, # BEQ -12 ; ea = $1002 + -12 = $ff6 ]) self.assertEqualHex(self.cpu.program_counter.value, 0xff6) def test_LBEQ_no(self): self.cpu.Z = 0 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x27, 0x07, 0xe4, # LBEQ +2020 ; ea = $1004 + 2020 = $17e8 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x1004) def test_LBEQ_yes(self): self.cpu.Z = 1 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x27, 0x07, 0xe4, # LBEQ +2020 ; ea = $1004 + 2020 = $17e8 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x17e8) def test_BGE_LBGE(self): for n, v in itertools.product(list(range(2)), repeat=2): # -> [(0, 0), (0, 1), (1, 0), (1, 1)] # print n, v, (n ^ v) == 0, n == v self.cpu.N = n self.cpu.V = v self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x2c, 0xf4, # BGE -12 ; ea = $1002 + -12 = $ff6 ]) # print "%s - $%04x" % (self.cpu.get_cc_info(), self.cpu.program_counter) if not operator.xor(n, v): # same as: (n ^ v) == 0: self.assertEqualHex(self.cpu.program_counter.value, 0xff6) else: self.assertEqualHex(self.cpu.program_counter.value, 0x1002) self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x2c, 0x07, 0xe4, # LBGE +2020 ; ea = $1004 + 2020 = $17e8 ]) if (n ^ v) == 0: self.assertEqualHex(self.cpu.program_counter.value, 0x17e8) else: self.assertEqualHex(self.cpu.program_counter.value, 0x1004) def test_BGT_LBGT(self): for n, v, z in itertools.product(list(range(2)), repeat=3): # -> [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), ..., (1, 1, 1)] # print n, v, (n ^ v) == 0, n == v self.cpu.N = n self.cpu.V = v self.cpu.Z = z self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x2e, 0xf4, # BGT -12 ; ea = $1002 + -12 = $ff6 ]) if n == v and z == 0: self.assertEqualHex(self.cpu.program_counter.value, 0xff6) else: self.assertEqualHex(self.cpu.program_counter.value, 0x1002) self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x2e, 0x07, 0xe4, # LBGT +2020 ; ea = $1004 + 2020 = $17e8 ]) if n == v and z == 0: self.assertEqualHex(self.cpu.program_counter.value, 0x17e8) else: self.assertEqualHex(self.cpu.program_counter.value, 0x1004) def test_BHI_LBHI(self): for c, z in itertools.product(list(range(2)), repeat=2): # -> [(0, 0), (0, 1), (1, 0), (1, 1)] self.cpu.C = c self.cpu.Z = z self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x22, 0xf4, # BHI -12 ; ea = $1002 + -12 = $ff6 ]) # print "%s - $%04x" % (self.cpu.get_cc_info(), self.cpu.program_counter) if c == 0 and z == 0: self.assertEqualHex(self.cpu.program_counter.value, 0xff6) else: self.assertEqualHex(self.cpu.program_counter.value, 0x1002) self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x22, 0x07, 0xe4, # LBHI +2020 ; ea = $1004 + 2020 = $17e8 ]) if c == 0 and z == 0: self.assertEqualHex(self.cpu.program_counter.value, 0x17e8) else: self.assertEqualHex(self.cpu.program_counter.value, 0x1004) def test_BHS_no(self): self.cpu.Z = 0 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x2f, 0xf4, # BHS -12 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x1002) def test_BHS_yes(self): self.cpu.Z = 1 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x2f, 0xf4, # BHS -12 ; ea = $1002 + -12 = $ff6 ]) self.assertEqualHex(self.cpu.program_counter.value, 0xff6) def test_LBHS_no(self): self.cpu.Z = 0 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x2f, 0x07, 0xe4, # LBHS +2020 ; ea = $1004 + 2020 = $17e8 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x1004) def test_LBHS_yes(self): self.cpu.Z = 1 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x2f, 0x07, 0xe4, # LBHS +2020 ; ea = $1004 + 2020 = $17e8 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x17e8) def test_BPL_no(self): self.cpu.N = 1 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x2a, 0xf4, # BPL -12 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x1002) def test_BPL_yes(self): self.cpu.N = 0 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x2a, 0xf4, # BPL -12 ; ea = $1002 + -12 = $ff6 ]) self.assertEqualHex(self.cpu.program_counter.value, 0xff6) def test_LBPL_no(self): self.cpu.N = 1 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x2a, 0x07, 0xe4, # LBPL +2020 ; ea = $1004 + 2020 = $17e8 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x1004) def test_LBPL_yes(self): self.cpu.N = 0 self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x2a, 0x07, 0xe4, # LBPL +2020 ; ea = $1004 + 2020 = $17e8 ]) self.assertEqualHex(self.cpu.program_counter.value, 0x17e8) def test_BLT_LBLT(self): for n, v in itertools.product(list(range(2)), repeat=2): # -> [(0, 0), (0, 1), (1, 0), (1, 1)] self.cpu.N = n self.cpu.V = v self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x2d, 0xf4, # BLT -12 ; ea = $1002 + -12 = $ff6 ]) # print "%s - $%04x" % (self.cpu.get_cc_info(), self.cpu.program_counter) if operator.xor(n, v): # same as: n ^ v == 1 self.assertEqualHex(self.cpu.program_counter.value, 0xff6) else: self.assertEqualHex(self.cpu.program_counter.value, 0x1002) self.cpu_test_run2(start=0x1000, count=1, mem=[ 0x10, 0x2d, 0x07, 0xe4, # LBLT +2020 ; ea = $1004 + 2020 = $17e8 ]) if operator.xor(n, v): self.assertEqualHex(self.cpu.program_counter.value, 0x17e8) else: self.assertEqualHex(self.cpu.program_counter.value, 0x1004)
class Test6809_BranchInstructions(BaseCPUTestCase): ''' Test branch instructions ''' def test_BCC_no(self): pass def test_BCC_yes(self): pass def test_LBCC_no(self): pass def test_LBCC_yes(self): pass def test_BCS_no(self): pass def test_BCS_yes(self): pass def test_LBCS_no(self): pass def test_LBCS_yes(self): pass def test_BEQ_no(self): pass def test_BEQ_yes(self): pass def test_LBEQ_no(self): pass def test_LBEQ_yes(self): pass def test_BGE_LBGE(self): pass def test_BGT_LBGT(self): pass def test_BHI_LBHI(self): pass def test_BHS_no(self): pass def test_BHS_yes(self): pass def test_LBHS_no(self): pass def test_LBHS_yes(self): pass def test_BPL_no(self): pass def test_BPL_yes(self): pass def test_LBPL_no(self): pass def test_LBPL_yes(self): pass def test_BLT_LBLT(self): pass
25
1
8
0
8
2
2
0.22
1
3
0
0
24
0
24
107
231
28
194
29
169
42
130
29
105
4
4
2
36
1,351
6809/MC6809
6809_MC6809/MC6809/example6809.py
MC6809.example6809.MC6809Example
class MC6809Example: def __init__(self): cfg = Config(CFG_DICT) memory = Memory(cfg) self.cpu = CPU(memory, cfg) def cpu_test_run(self, start, end, mem): assert isinstance(mem, bytearray), "given mem is not a bytearray!" print("memory load at $%x: %s", start, ", ".join(f"${i:x}" for i in mem) ) self.cpu.memory.load(start, mem) if end is None: end = start + len(mem) self.cpu.test_run(start, end) def crc32(self, data): """ Calculate a ZIP 32-bit CRC from data in memory. Origin code by Johann E. Klasek, j AT klasek at """ data_address = 0x1000 # position of the test data self.cpu.memory.load(data_address, data) # write test data into RAM self.cpu.index_x.set(data_address + len(data)) # end address addr_hi, addr_lo = divmod(data_address, 0x100) # start address self.cpu_test_run(start=0x0100, end=None, mem=bytearray([ # 0100| .ORG $100 0x10, 0xCE, 0x40, 0x00, # 0100| LDS #$4000 # 0104| CRCHH: EQU $ED # 0104| CRCHL: EQU $B8 # 0104| CRCLH: EQU $83 # 0104| CRCLL: EQU $20 # 0104| CRCINITH: EQU $FFFF # 0104| CRCINITL: EQU $FFFF # 0104| ; CRC 32 bit in DP (4 bytes) # 0104| CRC: EQU $80 0xCE, addr_hi, addr_lo, # 0104| LDU #.... ; start address in u 0x34, 0x10, # 010C| PSHS x ; end address +1 to TOS 0xCC, 0xFF, 0xFF, # 010E| LDD #CRCINITL 0xDD, 0x82, # 0111| STD crc+2 0x8E, 0xFF, 0xFF, # 0113| LDX #CRCINITH 0x9F, 0x80, # 0116| STX crc # 0118| ; d/x contains the CRC # 0118| BL: 0xE8, 0xC0, # 0118| EORB ,u+ ; XOR with lowest byte 0x10, 0x8E, 0x00, 0x08, # 011A| LDY #8 ; bit counter # 011E| RL: 0x1E, 0x01, # 011E| EXG d,x # 0120| RL1: 0x44, # 0120| LSRA ; shift CRC right, beginning with high word 0x56, # 0121| RORB 0x1E, 0x01, # 0122| EXG d,x 0x46, # 0124| RORA ; low word 0x56, # 0125| RORB 0x24, 0x12, # 0126| BCC cl # 0128| ; CRC=CRC XOR polynomic 0x88, 0x83, # 0128| EORA #CRCLH ; apply CRC polynomic low word 0xC8, 0x20, # 012A| EORB #CRCLL 0x1E, 0x01, # 012C| EXG d,x 0x88, 0xED, # 012E| EORA #CRCHH ; apply CRC polynomic high word 0xC8, 0xB8, # 0130| EORB #CRCHL 0x31, 0x3F, # 0132| LEAY -1,y ; bit count down 0x26, 0xEA, # 0134| BNE rl1 0x1E, 0x01, # 0136| EXG d,x ; CRC: restore correct order 0x27, 0x04, # 0138| BEQ el ; leave bit loop # 013A| CL: 0x31, 0x3F, # 013A| LEAY -1,y ; bit count down 0x26, 0xE0, # 013C| BNE rl ; bit loop # 013E| EL: 0x11, 0xA3, 0xE4, # 013E| CMPU ,s ; end address reached? 0x26, 0xD5, # 0141| BNE bl ; byte loop 0xDD, 0x82, # 0143| STD crc+2 ; CRC low word 0x9F, 0x80, # 0145| STX crc ; CRC high word ])) d = self.cpu.accu_d.value x = self.cpu.index_x.value crc32 = x * 0x10000 + d return crc32 ^ 0xFFFFFFFF def compare_crc32(self, data): data = bytes(data, encoding="ASCII") print(f"Compare CRC32 with: {data!r}") print("\nCreate CRC32 with binascii:") start_time = time.time() excpected_crc32 = binascii.crc32(data) & 0xffffffff duration = time.time() - start_time print(f"\tbinascii crc32..: ${excpected_crc32:X} calculated in {duration:.6f}sec") print("\nCreate CRC32 with Emulated 6809 CPU:") start_time = time.time() crc32_value = self.crc32(data) duration = time.time() - start_time print(f"\tMC6809 crc32..: ${crc32_value:X} calculated in {duration:.2f}sec") print() if crc32_value == excpected_crc32: print(" *** CRC32 values from 6809 and binascii are the same, ok.\n") return True else: print(" *** ERROR: CRC32 are different!\n") return False
class MC6809Example: def __init__(self): pass def cpu_test_run(self, start, end, mem): pass def crc32(self, data): ''' Calculate a ZIP 32-bit CRC from data in memory. Origin code by Johann E. Klasek, j AT klasek at ''' pass def compare_crc32(self, data): pass
5
1
25
2
19
14
2
0.72
0
5
3
0
4
1
4
4
105
9
76
17
71
55
41
17
36
2
0
1
6
1,352
6809/MC6809
6809_MC6809/MC6809/tests/test_6809_program.py
MC6809.tests.test_6809_program.Test6809_Program
class Test6809_Program(BaseStackTestCase): # def setUp(self): # self.UNITTEST_CFG_DICT["trace"] = True # super(Test6809_Program, self).setUp() def test_clear_loop(self): self.cpu_test_run(start=0x0100, end=None, mem=[ 0x8E, 0x00, 0x10, # L_B3BA ldx #$0010 ; clear 0 - 3ff 0x6F, 0x83, # L_B3BD clr ,--x 0x30, 0x01, # leax 1,x 0x26, 0xFA, # bne L_B3BD ]) print("TODO: Check result!") def _crc16(self, data): """ origin code by Johann E. Klasek, j AT klasek at """ data_address = 0x1000 # position of the test data self.cpu.memory.load(data_address, data) # write test data into RAM self.cpu.user_stack_pointer.set(data_address) # start address of data self.cpu.index_x.set(len(data)) # number of bytes self.cpu_test_run(start=0x0100, end=None, mem=[ # .ORG $100 # CRCH: EQU $10 # CRCL: EQU $21 # CRC16: # BL: 0xA8, 0xC0, # EORA ,u+ ; fetch byte and XOR into CRC high byte 0x10, 0x8E, 0x00, 0x08, # LDY #8 ; rotate loop counter 0x58, # RL: ASLB ; shift CRC left, first low 0x49, # ROLA ; and than high byte 0x24, 0x04, # BCC cl ; Justify or ... 0x88, 0x10, # EORA #CRCH ; CRC=CRC XOR polynomic, high 0xC8, 0x21, # EORB #CRCL ; and low byte 0x31, 0x3F, # CL: LEAY -1,y ; shift loop (8 bits) 0x26, 0xF4, # BNE rl 0x30, 0x1F, # LEAX -1,x ; byte loop 0x26, 0xEA, # BNE bl ]) crc16 = self.cpu.accu_d.value return crc16 def test_crc16_01(self): crc16 = self._crc16("Z") self.assertEqualHex(crc16, 0xfbbf) def test_crc16_02(self): crc16 = self._crc16("DragonPy works?!?") self.assertEqualHex(crc16, 0xA30D) def _crc32(self, data): """ Calculate a ZIP 32-bit CRC from data in memory. Origin code by Johann E. Klasek, j AT klasek at """ data_address = 0x1000 # position of the test data self.cpu.memory.load(data_address, data) # write test data into RAM self.cpu.index_x.set(data_address + len(data)) # end address addr_hi, addr_lo = divmod(data_address, 0x100) # start address self.cpu_test_run(start=0x0100, end=None, mem=[ # 0100| .ORG $100 0x10, 0xCE, 0x40, 0x00, # 0100| LDS #$4000 # 0104| CRCHH: EQU $ED # 0104| CRCHL: EQU $B8 # 0104| CRCLH: EQU $83 # 0104| CRCLL: EQU $20 # 0104| CRCINITH: EQU $FFFF # 0104| CRCINITL: EQU $FFFF # 0104| ; CRC 32 bit in DP (4 bytes) # 0104| CRC: EQU $80 0xCE, addr_hi, addr_lo, # 0104| LDU #.... ; start address in u 0x34, 0x10, # 010C| PSHS x ; end address +1 to TOS 0xCC, 0xFF, 0xFF, # 010E| LDD #CRCINITL 0xDD, 0x82, # 0111| STD crc+2 0x8E, 0xFF, 0xFF, # 0113| LDX #CRCINITH 0x9F, 0x80, # 0116| STX crc # 0118| ; d/x contains the CRC # 0118| BL: 0xE8, 0xC0, # 0118| EORB ,u+ ; XOR with lowest byte 0x10, 0x8E, 0x00, 0x08, # 011A| LDY #8 ; bit counter # 011E| RL: 0x1E, 0x01, # 011E| EXG d,x # 0120| RL1: 0x44, # 0120| LSRA ; shift CRC right, beginning with high word 0x56, # 0121| RORB 0x1E, 0x01, # 0122| EXG d,x 0x46, # 0124| RORA ; low word 0x56, # 0125| RORB 0x24, 0x12, # 0126| BCC cl # 0128| ; CRC=CRC XOR polynomic 0x88, 0x83, # 0128| EORA #CRCLH ; apply CRC polynomic low word 0xC8, 0x20, # 012A| EORB #CRCLL 0x1E, 0x01, # 012C| EXG d,x 0x88, 0xED, # 012E| EORA #CRCHH ; apply CRC polynomic high word 0xC8, 0xB8, # 0130| EORB #CRCHL 0x31, 0x3F, # 0132| LEAY -1,y ; bit count down 0x26, 0xEA, # 0134| BNE rl1 0x1E, 0x01, # 0136| EXG d,x ; CRC: restore correct order 0x27, 0x04, # 0138| BEQ el ; leave bit loop # 013A| CL: 0x31, 0x3F, # 013A| LEAY -1,y ; bit count down 0x26, 0xE0, # 013C| BNE rl ; bit loop # 013E| EL: 0x11, 0xA3, 0xE4, # 013E| CMPU ,s ; end address reached? 0x26, 0xD5, # 0141| BNE bl ; byte loop 0xDD, 0x82, # 0143| STD crc+2 ; CRC low word 0x9F, 0x80, # 0145| STX crc ; CRC high word ]) d = self.cpu.accu_d.value x = self.cpu.index_x.value crc32 = x * 0x10000 + d return crc32 ^ 0xFFFFFFFF def _test_crc32(self, txt): txt = bytes(txt, encoding="UTF-8") crc32 = self._crc32(txt) excpected_crc32 = binascii.crc32(txt) & 0xffffffff hex1 = f"${crc32:08x}" hex2 = f"${excpected_crc32:08x}" # print # print "Test String: %s" % repr(txt) # print "\tpython..:", hex1 # print "\tcrc32...:", hex2 self.assertEqual(hex1, hex2) def test_crc32_01(self): self._test_crc32("a09") # $3617c6fe def test_crc32_02(self): self._test_crc32("DragonPy test!") # $570e3666 def test_crc32_03(self): self._test_crc32("ZYXWVUTSRQPONMLKJIHGFEDBCA") # $99cdfdb2 # following tests works too but takes some time to run: # def test_crc32_04(self): # self._test_crc32("DragonPy Integration testing...") # $728b1186 # def test_crc32_05(self): # self._test_crc32("An Arbitrary String") # $6fbeaae7 # def test_crc32_06(self): # self._test_crc32("ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789") # $749f0b1a def _division(self, dividend, divisor): assert isinstance(dividend, int) assert isinstance(divisor, int) assert 0x0 <= dividend <= 0x100000000 assert 0x0 <= divisor <= 0x10000 a = [dividend >> (i << 3) & 0xff for i in (3, 2, 1, 0)] # print "a:", [hex(i) for i in a] b = [divisor >> (i << 3) & 0xff for i in (1, 0)] # print "b:", [hex(i) for i in b] """ orgigin code from Talbot System FIG Forth and modifyed by J.E. Klasek [email protected] see: https://github.com/6809/sbc09/blob/master/examples/uslash.asm """ self.cpu_test_run(start=0x0100, end=None, mem=[ # 0100| .ORG $100 # 0100| ; sample parameters on stack ... 0xCC, a[2], a[3], # 0100| LDD #$.... ; dividend low word 0x36, 0x06, # 0103| PSHU d 0xCC, a[0], a[1], # 0105| LDD #$.... ; dividend high word 0x36, 0x06, # 0108| PSHU d 0xCC, b[0], b[1], # 010A| LDD #$.... ; divisor word 0x36, 0x06, # 010D| PSHU d 0xEC, 0x42, # 010F| USLASH: LDD 2,u 0xAE, 0x44, # 0111| LDX 4,u 0xAF, 0x42, # 0113| STX 2,u 0xED, 0x44, # 0115| STD 4,u 0x68, 0x43, # 0117| ASL 3,u ; initial shift of L word 0x69, 0x42, # 0119| ROL 2,u 0x8E, 0x00, 0x10, # 011B| LDX #$10 0x69, 0x45, # 011E| USL1: ROL 5,u ; shift H word 0x69, 0x44, # 0120| ROL 4,u 0xEC, 0x44, # 0122| LDD 4,u 0xA3, 0xC4, # 0124| SUBD ,u ; does divisor fit? 0x1C, 0xFE, # 0126| ANDCC #$FE ; clc - clear carry flag 0x2B, 0x04, # 0128| BMI USL2 0xED, 0x44, # 012A| STD 4,u ; fits -> quotient = 1 0x1A, 0x01, # 012C| ORCC #$01 ; sec - Set Carry flag 0x69, 0x43, # 012E| USL2: ROL 3,u ; L word/quotient 0x69, 0x42, # 0130| ROL 2,u 0x30, 0x1F, # 0132| LEAX -1,x 0x26, 0xE8, # 0134| BNE USL1 0x33, 0x42, # 0136| LEAU 2,u 0xAE, 0xC4, # 0138| LDX ,u ; quotient 0xEC, 0x42, # 013A| LDD 2,u ; remainder ]) quotient = self.cpu.index_x.value remainder = self.cpu.accu_d.value return quotient, remainder def test_division(self): def test(dividend, divisor): """ dividend / divisor = quotient """ quotient, remainder = self._division(dividend, divisor) # print quotient, remainder a = Decimal(dividend) b = Decimal(divisor) expected_quotient = int(a // b) expected_remainder = int(a % b) first = f"{dividend:d}/{divisor:d}={quotient:d} remainder: {remainder:d}" second = ( f"{dividend:d}/{divisor:d}={expected_quotient:d} remainder: {expected_remainder:d}" ) self.assertEqual(first, second) test(10, 5) test(10, 3) test(1000, 2000) test(0xffff, 0x80) test(0xfffff, 0x800) test(0xffffff, 0x8000) test(0xfffffff, 0x8000) test(1, 0x8000)
class Test6809_Program(BaseStackTestCase): def test_clear_loop(self): pass def _crc16(self, data): ''' origin code by Johann E. Klasek, j AT klasek at ''' pass def test_crc16_01(self): pass def test_crc16_02(self): pass def _crc32(self, data): ''' Calculate a ZIP 32-bit CRC from data in memory. Origin code by Johann E. Klasek, j AT klasek at ''' pass def _test_crc32(self, txt): pass def test_crc32_01(self): pass def test_crc32_02(self): pass def test_crc32_03(self): pass def _division(self, dividend, divisor): pass def test_division(self): pass def test_clear_loop(self): ''' dividend / divisor = quotient ''' pass
13
3
18
1
13
11
1
0.93
1
3
0
1
11
0
11
95
226
21
150
37
137
140
70
37
57
1
5
0
12
1,353
6809/MC6809
6809_MC6809/MC6809/example6809.py
MC6809.example6809.Config
class Config(BaseConfig): RAM_START = 0x0000 RAM_END = 0x7FFF ROM_START = 0x8000 ROM_END = 0xFFFF
class Config(BaseConfig): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
5
6
1
5
5
4
0
5
5
4
0
1
0
0
1,354
6809/MC6809
6809_MC6809/MC6809/tests/test_6809_program.py
MC6809.tests.test_6809_program.Test6809_Program_Division2
class Test6809_Program_Division2(BaseStackTestCase): def _division(self, dividend, divisor): assert isinstance(dividend, int) assert isinstance(divisor, int) assert 0x0 <= dividend <= 0xffffffff assert 0x0 <= divisor <= 0xffff a = [dividend >> (i << 3) & 0xff for i in (3, 2, 1, 0)] # print "a:", [hex(i) for i in a] b = [divisor >> (i << 3) & 0xff for i in (1, 0)] # print "b:", [hex(i) for i in b] """ code from https://github.com/6809/sbc09 written by J.E. Klasek, replacing high-level variant in eFORTH. Special cases: 1. overflow: quotient overflow if dividend is to great (remainder = divisor), remainder is set to $FFFF -> special handling. This is checked also right before the main loop. 2. underflow: divisor does not fit into dividend -> remainder get the value of the dividend -> automatically covered. """ self.cpu_test_run(start=0x0000, end=None, mem=[ # 0000| EFORTH: # 0000| ; sample parameters on forth parameter stack (S) ... 0xCC, a[2], a[3], # 0000| LDD #$.... ; dividend low word 0x34, 0x06, # 0003| PSHS d 0xCC, a[0], a[1], # 0005| LDD #$.... ; dividend high word 0x34, 0x06, # 0008| PSHS d 0xCC, b[0], b[1], # 000A| LDD #$.... ; divisor 0x34, 0x06, # 000D| PSHS d # 000F| USLASH2: 0x8E, 0x00, 0x10, # 000F| LDX #16 0xEC, 0x62, # 0012| LDD 2,s ; udh 0x10, 0xA3, 0xE4, # 0014| CMPD ,s ; dividend to great? 0x24, 0x24, # 0017| BHS UMMODOV ; quotient overflow! 0x68, 0x65, # 0019| ASL 5,s ; udl low 0x69, 0x64, # 001B| ROL 4,s ; udl high 0x59, # 001D| UMMOD1: ROLB ; got one bit from udl 0x49, # 001E| ROLA 0x25, 0x09, # 001F| BCS UMMOD2 ; bit 16 means always greater as divisor 0x10, 0xA3, 0xE4, # 0021| CMPD ,s ; divide by un 0x24, 0x04, # 0024| BHS UMMOD2 ; higher or same as divisor? 0x1C, 0xFE, # 0026| ANDCC #$fe ; clc - clear carry flag 0x20, 0x04, # 0028| BRA UMMOD3 0xA3, 0xE4, # 002A| UMMOD2: SUBD ,s 0x1A, 0x01, # 002C| ORCC #$01 ; sec - set carry flag 0x69, 0x65, # 002E| UMMOD3: ROL 5,s ; udl, quotient shifted in 0x69, 0x64, # 0030| ROL 4,s 0x30, 0x1F, # 0032| LEAX -1,x 0x26, 0xE7, # 0034| BNE UMMOD1 0xAE, 0x64, # 0036| LDX 4,s ; quotient 0x10, 0xA3, 0xE4, # 0038| CMPD ,s ; remainder >= divisor -> overflow 0x25, 0x05, # 003B| BLO UMMOD4 # 003D| UMMODOV: 0xEC, 0xE4, # 003D| LDD ,s ; remainder set to divisor 0x8E, 0xFF, 0xFF, # 003F| LDX #$FFFF ; quotient = FFFF (-1) marks overflow # 0042| ; (case 1) # 0042| UMMOD4: 0x32, 0x62, # 0042| LEAS 2,s ; un (divisor thrown away) 0xAF, 0xE4, # 0044| STX ,s ; quotient to TOS 0xED, 0x62, # 0046| STD 2,s ; remainder 2nd 0x20, 0x02, # 0048| BRA $0 ;realexit # 004A| ; not reached 0x37, 0x80, # 004A| PULU pc ; eFORTH NEXT # 0051| EXIT: ]) quotient = self.cpu.index_x.value remainder = self.cpu.accu_d.value return quotient, remainder def test_division(self): def test(dividend, divisor): """ dividend / divisor = quotient """ quotient, remainder = self._division(dividend, divisor) a = Decimal(dividend) b = Decimal(divisor) expected_quotient = a // b expected_remainder = a % b # print "$%x / $%x" % (dividend, divisor) first = "%i/%i=%i remainder: %i (hex: q:$%x r:=$%x)" % ( dividend, divisor, quotient, remainder, quotient, remainder, ) second = "%i/%i=%i remainder: %i (hex: q:$%x r:=$%x)" % ( dividend, divisor, expected_quotient, expected_remainder, int(expected_quotient), int(expected_remainder) ) # if first != second: # print "ERROR: %r should be: %r\n" % (first, second) # else: # print "OK: %s\n" % first self.assertEqual(first, second) test(10, 10) # OK: 10/10=1 remainder: 0 test(10, 5) # OK: 10/5=2 remainder: 0 test(10, 3) # OK: 10/3=3 remainder: 1 test(0xffff, 0x80) # OK: 65535/128=511 remainder: 127 test(0xffff, 0xff) # OK: 65535/255=257 remainder: 0 test(0xfffff, 0x800) # OK: 1048575/2048=511 remainder: 2047 test(0xffffff, 0x8000) # OK: 16777215/32768=511 remainder: 32767 test(0xfffffff, 0x8000) # OK: 268435455/32768=8191 remainder: 32767 test(0xfffffff, 0xffff) # OK: 268435455/65535=4096 remainder: 4095 test(1, 0xffff) # OK: 1/65535=0 remainder: 1 test(1, 0x8000) # OK: 1/32768=0 remainder: 1 def test_overflow(self): """ overflow (quotient is > $FFFF) quotient = $FFFF, remainder = divisor """ quotient, remainder = self._division(0x10000, 0x1) self.assertEqualHexWord(quotient, 0xffff) self.assertEqualHexWord(remainder, 0x1) def test_division_by_zero(self): quotient, remainder = self._division(0x1, 0x0) self.assertEqualHexWord(quotient, 0xffff) self.assertEqualHexWord(remainder, 0)
class Test6809_Program_Division2(BaseStackTestCase): def _division(self, dividend, divisor): pass def test_division(self): pass def test_division(self): ''' dividend / divisor = quotient ''' pass def test_overflow(self): ''' overflow (quotient is > $FFFF) quotient = $FFFF, remainder = divisor ''' pass def test_division_by_zero(self): pass
6
2
28
1
19
17
1
0.94
1
2
0
0
4
0
4
88
123
8
83
19
77
78
41
19
35
1
5
0
5
1,355
6809/MC6809
6809_MC6809/MC6809/core/memory_info.py
MC6809.core.memory_info.BaseMemoryInfo
class BaseMemoryInfo: def __init__(self, out_func): self.out_func = out_func def get_shortest(self, addr): shortest = None size = sys.maxsize for start, end, txt in self.MEM_INFO: if not start <= addr <= end: continue current_size = abs(end - start) if current_size < size: size = current_size shortest = start, end, txt if shortest is None: return f"${addr:x}: UNKNOWN" start, end, txt = shortest if start == end: return f"${addr:x}: {txt}" else: return f"${addr:x}: ${start:x}-${end:x} - {txt}" def __call__(self, addr, info="", shortest=True): if shortest: mem_info = self.get_shortest(addr) if info: self.out_func(f"{info}: {mem_info}") else: self.out_func(mem_info) return mem_info = [] for start, end, txt in self.MEM_INFO: if start <= addr <= end: mem_info.append( (start, end, txt) ) if not mem_info: self.out_func(f"{info} ${addr:x}: UNKNOWN") else: self.out_func(f"{info} ${addr:x}:") for start, end, txt in mem_info: if start == end: self.out_func(f" * ${start:x} - {txt}") else: self.out_func(f" * ${start:x}-${end:x} - {txt}")
class BaseMemoryInfo: def __init__(self, out_func): pass def get_shortest(self, addr): pass def __call__(self, addr, info="", shortest=True): pass
4
0
16
2
14
0
5
0
0
0
0
0
3
1
3
3
50
7
43
11
39
0
37
11
33
8
0
3
15
1,356
6809/MC6809
6809_MC6809/MC6809/tests/test_6809_address_modes.py
MC6809.tests.test_6809_address_modes.Test6809_AddressModes_LowLevel
class Test6809_AddressModes_LowLevel(BaseCPUTestCase): def test_base_page_direct01(self): self.cpu.memory.load(0x1000, [0x12, 0x34, 0x0f]) self.cpu.program_counter.set(0x1000) self.cpu.direct_page.set(0xab) ea = self.cpu.get_ea_direct() self.assertEqualHexWord(ea, 0xab12) ea = self.cpu.get_ea_direct() self.assertEqualHexWord(ea, 0xab34) self.cpu.direct_page.set(0x0) ea = self.cpu.get_ea_direct() self.assertEqualHexByte(ea, 0xf)
class Test6809_AddressModes_LowLevel(BaseCPUTestCase): def test_base_page_direct01(self): pass
2
0
14
3
11
0
1
0
1
0
0
0
1
0
1
84
15
3
12
3
10
0
12
3
10
1
4
0
1
1,357
6809/MC6809
6809_MC6809/MC6809/tests/test_6809_address_modes.py
MC6809.tests.test_6809_address_modes.Test6809_AddressModes_Indexed
class Test6809_AddressModes_Indexed(BaseCPUTestCase): def test_5bit_signed_offset_01(self): self.cpu.index_x.set(0x0300) self.cpu.index_y.set(0x1234) self.cpu_test_run(start=0x1b5c, end=None, mem=[0x10, 0xAF, 0x04]) # STY 4,X self.assertEqualHexWord(self.cpu.memory.read_word(0x0304), 0x1234) # $0300 + $04 = $0304 def test_5bit_signed_offset_02(self): """ LDX #$abcd LDY #$50 STX -16,Y """ self.cpu.index_x.set(0xabcd) self.cpu.index_y.set(0x0050) self.cpu_test_run(start=0x1b5c, end=None, mem=[0xAF, 0x30]) # STX -16,Y self.assertEqualHexWord(self.cpu.memory.read_word(0x0040), 0xabcd) # $0050 + $-10 = $0040 def test_increment_by_1(self): self.cpu_test_run(start=0x2000, end=None, mem=[ 0x8E, 0xAB, 0xCD, # 0000| LDX #$abcd ;set X to $abcd 0x10, 0x8E, 0x00, 0x50, # 0003| LDY #$50 ;set Y to $0050 0xAF, 0xA0, # 0007| STX ,Y+ ;store X at $50 and Y+1 0x10, 0x9F, 0x58, # 0009| STY $58 ;store Y at $58 ]) self.assertEqualHexWord(self.cpu.memory.read_word(0x0050), 0xabcd) self.assertEqualHexWord(self.cpu.memory.read_word(0x0058), 0x0051) def test_increment_by_2(self): self.cpu_test_run(start=0x2000, end=None, mem=[ 0x8E, 0xAB, 0xCD, # 0000| LDX #$abcd ;set X to $abcd 0x10, 0x8E, 0x00, 0x50, # 0003| LDY #$50 ;set Y to $0050 0xAF, 0xA1, # 0007| STX ,Y++ ;store X at $50 and Y+2 0x10, 0x9F, 0x58, # 0009| STY $58 ;store Y at $58 ]) self.assertEqualHexWord(self.cpu.memory.read_word(0x0050), 0xabcd) self.assertEqualHexWord(self.cpu.memory.read_word(0x0058), 0x0052) def test_decrement_by_1(self): self.cpu_test_run(start=0x2000, end=None, mem=[ 0x8E, 0xAB, 0xCD, # 0000| LDX #$abcd ;set X to $abcd 0x10, 0x8E, 0x00, 0x50, # 0003| LDY #$50 ;set Y to $0050 0xAF, 0xA2, # 0007| STX ,-Y ;Y-1 and store X at $50-1 0x10, 0x9F, 0x58, # 0009| STY $58 ;store Y at $58 ]) self.assertEqualHexWord(self.cpu.memory.read_word(0x004f), 0xabcd) # 50-1 self.assertEqualHexWord(self.cpu.memory.read_word(0x0058), 0x004f) def test_decrement_by_2(self): self.cpu_test_run(start=0x2000, end=None, mem=[ 0x8E, 0xAB, 0xCD, # 0000| LDX #$abcd ;set X to $abcd 0x10, 0x8E, 0x00, 0x50, # 0003| LDY #$50 ;set Y to $0050 0xAF, 0xA3, # 0007| STX ,--Y ;Y-2 and store X at $50-1 0x10, 0x9F, 0x58, # 0009| STY $58 ;store Y at $58 ]) self.assertEqualHexWord(self.cpu.memory.read_word(0x004e), 0xabcd) # 50-2 self.assertEqualHexWord(self.cpu.memory.read_word(0x0058), 0x004e) def test_no_offset(self): self.cpu_test_run(start=0x2000, end=None, mem=[ 0x8E, 0xAB, 0xCD, # 0000| LDX #$abcd ;set X to $abcd 0x10, 0x8E, 0x00, 0x50, # 0003| LDY #$50 ;set Y to $0050 0xAF, 0xA4, # 0007| STX ,Y ;store X at $50 0x10, 0x9F, 0x58, # 0009| STY $58 ;store Y at $58 ]) self.assertEqualHexWord(self.cpu.memory.read_word(0x0050), 0xabcd) # X self.assertEqualHexWord(self.cpu.memory.read_word(0x0058), 0x0050) # Y def test_B_offset(self): self.cpu_test_run(start=0x2000, end=None, mem=[ 0xC6, 0x03, # LDB #$3 ; set B to $3 0x8E, 0xAB, 0xCD, # LDX #$abcd ; set X to $abcd 0x10, 0x8E, 0x00, 0x50, # LDY #$50 ; set Y to $50 0xAF, 0xA5, # STX B,Y ; store X at Y and B 0x10, 0x9F, 0x58, # STY $58 ; store Y ]) self.assertEqualHexWord(self.cpu.memory.read_word(0x0050 + 0x03), 0xabcd) # 53 self.assertEqualHexWord(self.cpu.memory.read_word(0x0058), 0x0050) # Y def test_A_offset(self): self.cpu_test_run(start=0x2000, end=None, mem=[ 0x86, 0xFC, # LDA #$-4 ; set A to $-4 0x8E, 0xAB, 0xCD, # LDX #$abcd ; set X to $abcd 0x10, 0x8E, 0x00, 0x50, # LDY #$50 ; set Y to $50 0xAF, 0xA6, # STX A,Y ; store X at Y and A 0x10, 0x9F, 0x58, # STY $58 ; store Y ]) self.assertEqualHexWord(self.cpu.memory.read_word(0x0050 - 0x04), 0xabcd) # 4c self.assertEqualHexWord(self.cpu.memory.read_word(0x0058), 0x0050) # Y def test_8bit_offset(self): x = 0xabcd y = 0x00d0 offset = 0x80 # signed = $-80 self.cpu.index_x.set(x) self.cpu.index_y.set(y) self.cpu_test_run(start=0x2000, end=None, mem=[ 0xAF, 0xA8, offset, # STX $30,Y ; store X at Y -80 = $50 ]) self.assertEqualHexWord(self.cpu.index_y.value, y) self.assertEqualHexWord(self.cpu.memory.read_word(0x50), x) # $d0 + $-80 = $50 def test_16bit_offset(self): """ LDX #$abcd ; set X to $abcd LDY #$804f ; set Y to $804f STX $8001,Y ; store X at Y + $-7fff STY $20 ; store Y at $20 """ x = 0xabcd y = 0x804f offset = 0x8001 # signed = $-7fff offset_hi, offset_lo = divmod(offset, 0x100) self.cpu.index_x.set(x) self.cpu.index_y.set(y) self.cpu_test_run(start=0x2000, end=None, mem=[ 0xAF, 0xA9, offset_hi, offset_lo, # STX $8001,Y ; store X at Y + $-7fff ]) self.assertEqualHexWord(self.cpu.index_y.value, y) self.assertEqualHexWord(self.cpu.memory.read_word(0x50), x) # $804f + $-7fff = $50 def test_D_offset(self): """ LDX #$abcd ; set X to $abcd LDY #$804f ; set Y to $804f LDD #$8001 ; set D to $8001 signed = $-7fff STX D,Y ; store X at $50 (Y + D) STY $20 ; store Y at $20 """ x = 0xabcd y = 0x804f d = 0x8001 # signed = $-7fff self.cpu.index_x.set(x) self.cpu.index_y.set(y) self.cpu.accu_d.set(d) self.cpu_test_run(start=0x2000, end=None, mem=[ 0xAF, 0xAB, # STX D,Y ; store X at Y + D ]) self.assertEqualHexWord(self.cpu.index_x.value, x) # $804f + $-7fff = $50 self.assertEqualHexWord(self.cpu.memory.read_word(0x50), x) # $804f + $-7fff = $50 def test_pc_offset_8bit_positive(self): x = 0xabcd self.cpu.index_x.set(x) self.cpu_test_run(start=0x2000, end=None, mem=[ 0xAF, 0x8C, 0x12, # STX 12,PC ]) self.assertEqualHexWord(self.cpu.index_x.value, x) # ea = pc($2003) + $12 = $2015 self.assertEqualHexWord(self.cpu.memory.read_word(0x2015), x) def test_pc_offset_8bit_negative(self): a = 0x56 self.cpu.accu_a.set(a) self.cpu_test_run(start=0x1000, end=None, mem=[ 0xA7, 0x8C, 0x80, # STA 12,PC ]) self.assertEqualHexByte(self.cpu.accu_a.value, a) # ea = pc($1003) + $-80 = $f83 self.assertEqualHexByte(self.cpu.memory.read_byte(0x0f83), a) def test_pc_offset_16bit_positive(self): x = 0xabcd self.cpu.index_x.set(x) self.cpu_test_run(start=0x2000, end=None, mem=[ 0xAF, 0x8D, 0x0a, 0xb0, # STX 1234,PC ]) self.assertEqualHexWord(self.cpu.index_x.value, x) # ea = pc($2004) + $ab0 = $2ab4 self.assertEqualHexWord(self.cpu.memory.read_word(0x2ab4), x) def test_pc_offset_16bit_negative(self): a = 0x56 self.cpu.accu_a.set(a) self.cpu_test_run(start=0x1000, end=None, mem=[ 0xA7, 0x8D, 0xf0, 0x10, # STA 12,PC ]) self.assertEqualHexByte(self.cpu.accu_a.value, a) # ea = pc($1004) + $-ff0 = $14 self.assertEqualHexByte(self.cpu.memory.read_byte(0x0014), a) def test_indirect_addressing(self): print("TODO!!!")
class Test6809_AddressModes_Indexed(BaseCPUTestCase): def test_5bit_signed_offset_01(self): pass def test_5bit_signed_offset_02(self): ''' LDX #$abcd LDY #$50 STX -16,Y ''' pass def test_increment_by_1(self): pass def test_increment_by_2(self): pass def test_decrement_by_1(self): pass def test_decrement_by_2(self): pass def test_no_offset(self): pass def test_B_offset(self): pass def test_A_offset(self): pass def test_8bit_offset(self): pass def test_16bit_offset(self): ''' LDX #$abcd ; set X to $abcd LDY #$804f ; set Y to $804f STX $8001,Y ; store X at Y + $-7fff STY $20 ; store Y at $20 ''' pass def test_D_offset(self): ''' LDX #$abcd ; set X to $abcd LDY #$804f ; set Y to $804f LDD #$8001 ; set D to $8001 signed = $-7fff STX D,Y ; store X at $50 (Y + D) STY $20 ; store Y at $20 ''' pass def test_pc_offset_8bit_positive(self): pass def test_pc_offset_8bit_negative(self): pass def test_pc_offset_16bit_positive(self): pass def test_pc_offset_16bit_negative(self): pass def test_indirect_addressing(self): pass
18
3
10
0
8
5
1
0.54
1
0
0
0
17
0
17
100
184
16
145
32
127
78
94
32
76
1
4
0
17
1,358
6809/MC6809
6809_MC6809/MC6809/tests/test_6809_StoreLoad.py
MC6809.tests.test_6809_StoreLoad.Test6809_Load
class Test6809_Load(BaseStackTestCase): def test_LDD_immediate(self): self.cpu.accu_d.set(0) self.cpu_test_run(start=0x4000, end=None, mem=[0xCC, 0xfe, 0x12]) # LDD $fe12 (Immediate) self.assertEqualHex(self.cpu.accu_d.value, 0xfe12) def test_LDD_extended(self): self.cpu.memory.write_word(0x5020, 0x1234) self.cpu_test_run(start=0x4000, end=None, mem=[0xFC, 0x50, 0x20]) # LDD $5020 (Extended) self.assertEqualHex(self.cpu.accu_d.value, 0x1234)
class Test6809_Load(BaseStackTestCase): def test_LDD_immediate(self): pass def test_LDD_extended(self): pass
3
0
4
0
4
1
1
0.22
1
0
0
0
2
0
2
86
10
1
9
3
6
2
9
3
6
1
5
0
2
1,359
6809/MC6809
6809_MC6809/MC6809/core/configs.py
MC6809.core.configs.DummyMemInfo
class DummyMemInfo: def get_shortest(self, *args): return ">>mem info not active<<" def __call__(self, *args): return ">>mem info not active<<"
class DummyMemInfo: def get_shortest(self, *args): pass def __call__(self, *args): pass
3
0
2
0
2
0
1
0
0
0
0
0
2
0
2
2
6
1
5
3
2
0
5
3
2
1
0
0
2
1,360
6809/MC6809
6809_MC6809/MC6809/core/cpu_control_server.py
MC6809.core.cpu_control_server.ControlHandler
class ControlHandler(BaseHTTPRequestHandler): def __init__(self, request, client_address, server, cpu): log.error("ControlHandler %s %s %s", request, client_address, server) self.cpu = cpu self.get_urls = { r"/disassemble/(\s+)/$": self.get_disassemble, r"/memory/(\s+)(-(\s+))?/$": self.get_memory, r"/memory/(\s+)(-(\s+))?/raw/$": self.get_memory_raw, r"/status/$": self.get_status, r"/$": self.get_index, } self.post_urls = { r"/memory/(\s+)(-(\s+))?/$": self.post_memory, r"/memory/(\s+)(-(\s+))?/raw/$": self.post_memory_raw, r"/quit/$": self.post_quit, r"/reset/$": self.post_reset, r"/debug/$": self.post_debug, } BaseHTTPRequestHandler.__init__(self, request, client_address, server) def log_message(self, format, *args): msg = f"{self.client_address[0]} - - [{self.log_date_time_string()}] {format % args}\n" log.critical(msg) def dispatch(self, urls): for r, f in list(urls.items()): m = re.match(r, self.path) if m is not None: log.critical("call %s", f.__name__) try: f(m) except Exception as err: txt = traceback.format_exc() self.response_500(f"Error call {f.__name__!r}: {err}", txt) return else: self.response_404(f"url {self.path!r} doesn't match any urls") def response(self, s, status_code=200): log.critical("send %s response", status_code) self.send_response(status_code) self.send_header("Content-Length", str(len(s))) self.end_headers() self.wfile.write(s) def response_html(self, headline, text=""): html = ( "<!DOCTYPE html><html><body>" "<h1>%s</h1>" "%s" "</body></html>" ) % (headline, text) self.response(html) def response_404(self, txt): log.error(txt) html = ( "<!DOCTYPE html><html><body>" "<h1>DragonPy - 6809 CPU control server</h1>" "<h2>404 - Error:</h2>" "<p>%s</p>" "</body></html>" ) % txt self.response(html, status_code=404) def response_500(self, err, tb_txt): log.error(err, tb_txt) html = ( "<!DOCTYPE html><html><body>" "<h1>DragonPy - 6809 CPU control server</h1>" "<h2>500 - Error:</h2>" "<p>%s</p>" "<pre>%s</pre>" "</body></html>" ) % (err, tb_txt) self.response(html, status_code=500) def do_GET(self): log.critical("do_GET(): %r", self.path) self.dispatch(self.get_urls) def do_POST(self): log.critical("do_POST(): %r", self.path) self.dispatch(self.post_urls) def get_index(self, m): self.response_html( headline="DragonPy - 6809 CPU control server", text=( "<p>Example urls:" "<ul>" '<li>CPU status:<a href="/status/">/status/</a></li>' '<li>6809 interrupt vectors memory dump:' '<a href="/memory/fff0-ffff/">/memory/fff0-ffff/</a></li>' '</ul>' '<form action="/quit/" method="post">' '<input type="submit" value="Quit CPU">' '</form>' )) def get_disassemble(self, m): addr = int(m.group(1)) r = [] n = 20 while n > 0: dis, length = self.disassemble.disasm(addr) r.append(dis) addr += length n -= 1 self.response(json.dumps(r)) def get_memory_raw(self, m): addr = int(m.group(1)) e = m.group(3) if e is not None: end = int(e) else: end = addr self.response("".join(chr(self.cpu.read_byte(x)) for x in range(addr, end + 1))) def get_memory(self, m): addr = int(m.group(1), 16) e = m.group(3) if e is not None: end = int(e, 16) else: end = addr self.response(json.dumps(list(map(self.cpu.read_byte, list(range(addr, end + 1)))))) def get_status(self, m): data = { "cpu": self.cpu.get_info, "cc": self.cpu.get_cc_info(), "pc": self.cpu.program_counter.get(), "cycle_count": self.cpu.cycles, } log.critical("status dict: %s", repr(data)) json_string = json.dumps(data) self.response(json_string) def post_memory(self, m): addr = int(m.group(1)) e = m.group(3) if e is not None: end = int(e) else: end = addr data = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) for i, a in enumerate(range(addr, end + 1)): self.cpu.write_byte(a, data[i]) self.response("") def post_memory_raw(self, m): addr = int(m.group(1)) e = m.group(3) if e is not None: end = int(e) else: end = addr data = self.rfile.read(int(self.headers["Content-Length"])) for i, a in enumerate(range(addr, end + 1)): self.cpu.write_byte(a, data[i]) self.response("") def post_debug(self, m): handler = logging.StreamHandler() handler.level = 5 log.handlers = (handler,) log.critical("Activate full debug logging in %s!", __file__) self.response("") def post_quit(self, m): log.critical("Quit CPU from controller server.") self.cpu.quit() self.response_html(headline="CPU running") def post_reset(self, m): self.cpu.reset() self.response_html(headline="CPU reset")
class ControlHandler(BaseHTTPRequestHandler): def __init__(self, request, client_address, server, cpu): pass def log_message(self, format, *args): pass def dispatch(self, urls): pass def response(self, s, status_code=200): pass def response_html(self, headline, text=""): pass def response_404(self, txt): pass def response_500(self, err, tb_txt): pass def do_GET(self): pass def do_POST(self): pass def get_index(self, m): pass def get_disassemble(self, m): pass def get_memory_raw(self, m): pass def get_memory_raw(self, m): pass def get_status(self, m): pass def post_memory(self, m): pass def post_memory_raw(self, m): pass def post_debug(self, m): pass def post_quit(self, m): pass def post_reset(self, m): pass
20
0
9
0
8
0
2
0
1
8
0
0
19
3
19
42
183
22
161
54
141
0
110
53
90
4
3
3
29
1,361
6809/MC6809
6809_MC6809/MC6809/components/cpu_utils/MC6809_registers.py
MC6809.components.cpu_utils.MC6809_registers.ValueStorageBase
class ValueStorageBase: def __init__(self, name, initial_value): self.name = name self.value = initial_value def set(self, v): self.value = v def decrement(self, value=1): self.set(self.value - value) def increment(self, value=1): self.set(self.value + value) def __str__(self): return f"<{self.name}:${self.value:x}>" __repr__ = __str__
class ValueStorageBase: def __init__(self, name, initial_value): pass def set(self, v): pass def decrement(self, value=1): pass def increment(self, value=1): pass def __str__(self): pass
6
0
2
0
2
0
1
0
0
0
0
3
5
2
5
5
17
4
13
9
7
0
13
9
7
1
0
0
5
1,362
6809/MC6809
6809_MC6809/MC6809/components/cpu_utils/instruction_base.py
MC6809.components.cpu_utils.instruction_base.InstructionBase
class InstructionBase: def __init__(self, cpu, instr_func): self.cpu = cpu self.instr_func = instr_func def special(self, opcode): # e.g: RESET and PAGE 1/2 return self.instr_func(opcode)
class InstructionBase: def __init__(self, cpu, instr_func): pass def special(self, opcode): pass
3
0
3
0
3
1
1
0.17
0
0
0
1
2
2
2
2
8
1
6
5
3
1
6
5
3
1
0
0
2
1,363
6809/MC6809
6809_MC6809/MC6809/components/cpu_utils/instruction_call.py
MC6809.components.cpu_utils.instruction_call.PrepagedInstructions
class PrepagedInstructions(InstructionBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.write_byte = self.cpu.memory.write_byte self.write_word = self.cpu.memory.write_word self.accu_a = self.cpu.accu_a self.accu_b = self.cpu.accu_b self.accu_d = self.cpu.accu_d self.cc_register = self.cpu.cc_register self.index_x = self.cpu.index_x self.index_y = self.cpu.index_y self.system_stack_pointer = self.cpu.system_stack_pointer self.user_stack_pointer = self.cpu.user_stack_pointer self.get_ea_direct = self.cpu.get_ea_direct self.get_ea_extended = self.cpu.get_ea_extended self.get_ea_indexed = self.cpu.get_ea_indexed self.get_ea_m_direct = self.cpu.get_ea_m_direct self.get_ea_m_extended = self.cpu.get_ea_m_extended self.get_ea_m_indexed = self.cpu.get_ea_m_indexed self.get_ea_relative = self.cpu.get_ea_relative self.get_ea_relative_word = self.cpu.get_ea_relative_word self.get_m_direct = self.cpu.get_m_direct self.get_m_direct_word = self.cpu.get_m_direct_word self.get_m_extended = self.cpu.get_m_extended self.get_m_extended_word = self.cpu.get_m_extended_word self.get_m_immediate = self.cpu.get_m_immediate self.get_m_immediate_word = self.cpu.get_m_immediate_word self.get_m_indexed = self.cpu.get_m_indexed self.get_m_indexed_word = self.cpu.get_m_indexed_word def direct_A_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_direct(), register=self.accu_a, ) def direct_B_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_direct(), register=self.accu_b, ) def direct_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_direct(), ) def direct_ea_A_write8(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_direct(), register=self.accu_a, ) self.write_byte(ea, value) def direct_ea_B_write8(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_direct(), register=self.accu_b, ) self.write_byte(ea, value) def direct_ea_D_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_direct(), register=self.accu_d, ) self.write_word(ea, value) def direct_ea_read8_write8(self, opcode): ea, m = self.cpu.get_ea_m_direct() ea, value = self.instr_func( opcode=opcode, ea=ea, m=m, ) self.write_byte(ea, value) def direct_ea_write8(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_direct(), ) self.write_byte(ea, value) def direct_ea(self, opcode): self.instr_func( opcode=opcode, ea=self.get_ea_direct(), ) def direct_ea_S_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_direct(), register=self.system_stack_pointer, ) self.write_word(ea, value) def direct_ea_U_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_direct(), register=self.user_stack_pointer, ) self.write_word(ea, value) def direct_ea_X_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_direct(), register=self.index_x, ) self.write_word(ea, value) def direct_ea_Y_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_direct(), register=self.index_y, ) self.write_word(ea, value) def direct_word_D_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_direct_word(), register=self.accu_d, ) def direct_word_S_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_direct_word(), register=self.system_stack_pointer, ) def direct_word_U_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_direct_word(), register=self.user_stack_pointer, ) def direct_word_X_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_direct_word(), register=self.index_x, ) def direct_word_Y_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_direct_word(), register=self.index_y, ) def extended_A_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_extended(), register=self.accu_a, ) def extended_B_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_extended(), register=self.accu_b, ) def extended_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_extended(), ) def extended_ea_A_write8(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_extended(), register=self.accu_a, ) self.write_byte(ea, value) def extended_ea_B_write8(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_extended(), register=self.accu_b, ) self.write_byte(ea, value) def extended_ea_D_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_extended(), register=self.accu_d, ) self.write_word(ea, value) def extended_ea_read8_write8(self, opcode): ea, m = self.cpu.get_ea_m_extended() ea, value = self.instr_func( opcode=opcode, ea=ea, m=m, ) self.write_byte(ea, value) def extended_ea_write8(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_extended(), ) self.write_byte(ea, value) def extended_ea(self, opcode): self.instr_func( opcode=opcode, ea=self.get_ea_extended(), ) def extended_ea_S_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_extended(), register=self.system_stack_pointer, ) self.write_word(ea, value) def extended_ea_U_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_extended(), register=self.user_stack_pointer, ) self.write_word(ea, value) def extended_ea_X_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_extended(), register=self.index_x, ) self.write_word(ea, value) def extended_ea_Y_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_extended(), register=self.index_y, ) self.write_word(ea, value) def extended_word_D_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_extended_word(), register=self.accu_d, ) def extended_word_S_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_extended_word(), register=self.system_stack_pointer, ) def extended_word_U_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_extended_word(), register=self.user_stack_pointer, ) def extended_word_X_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_extended_word(), register=self.index_x, ) def extended_word_Y_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_extended_word(), register=self.index_y, ) def immediate_A_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_immediate(), register=self.accu_a, ) def immediate_B_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_immediate(), register=self.accu_b, ) def immediate_CC_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_immediate(), register=self.cc_register, ) def immediate_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_immediate(), ) def immediate_S_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_immediate(), register=self.system_stack_pointer, ) def immediate_U_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_immediate(), register=self.user_stack_pointer, ) def immediate_word_D_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_immediate_word(), register=self.accu_d, ) def immediate_word_S_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_immediate_word(), register=self.system_stack_pointer, ) def immediate_word_U_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_immediate_word(), register=self.user_stack_pointer, ) def immediate_word_X_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_immediate_word(), register=self.index_x, ) def immediate_word_Y_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_immediate_word(), register=self.index_y, ) def indexed_A_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_indexed(), register=self.accu_a, ) def indexed_B_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_indexed(), register=self.accu_b, ) def indexed_read8(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_indexed(), ) def indexed_ea_A_write8(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), register=self.accu_a, ) self.write_byte(ea, value) def indexed_ea_B_write8(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), register=self.accu_b, ) self.write_byte(ea, value) def indexed_ea_D_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), register=self.accu_d, ) self.write_word(ea, value) def indexed_ea_read8_write8(self, opcode): ea, m = self.cpu.get_ea_m_indexed() ea, value = self.instr_func( opcode=opcode, ea=ea, m=m, ) self.write_byte(ea, value) def indexed_ea_write8(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), ) self.write_byte(ea, value) def indexed_ea(self, opcode): self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), ) def indexed_ea_S_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), register=self.system_stack_pointer, ) self.write_word(ea, value) def indexed_ea_S(self, opcode): self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), register=self.system_stack_pointer, ) def indexed_ea_U_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), register=self.user_stack_pointer, ) self.write_word(ea, value) def indexed_ea_U(self, opcode): self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), register=self.user_stack_pointer, ) def indexed_ea_X_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), register=self.index_x, ) self.write_word(ea, value) def indexed_ea_X(self, opcode): self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), register=self.index_x, ) def indexed_ea_Y_write16(self, opcode): ea, value = self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), register=self.index_y, ) self.write_word(ea, value) def indexed_ea_Y(self, opcode): self.instr_func( opcode=opcode, ea=self.get_ea_indexed(), register=self.index_y, ) def indexed_word_D_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_indexed_word(), register=self.accu_d, ) def indexed_word_S_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_indexed_word(), register=self.system_stack_pointer, ) def indexed_word_U_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_indexed_word(), register=self.user_stack_pointer, ) def indexed_word_X_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_indexed_word(), register=self.index_x, ) def indexed_word_Y_read16(self, opcode): self.instr_func( opcode=opcode, m=self.get_m_indexed_word(), register=self.index_y, ) def inherent_A(self, opcode): self.instr_func( opcode=opcode, register=self.accu_a, ) def inherent_B(self, opcode): self.instr_func( opcode=opcode, register=self.accu_b, ) def inherent(self, opcode): self.instr_func( opcode=opcode, ) def relative_ea(self, opcode): self.instr_func( opcode=opcode, ea=self.get_ea_relative(), ) def relative_word_ea(self, opcode): self.instr_func( opcode=opcode, ea=self.get_ea_relative_word(), )
class PrepagedInstructions(InstructionBase): def __init__(self, *args, **kwargs): pass def direct_A_read8(self, opcode): pass def direct_B_read8(self, opcode): pass def direct_read8(self, opcode): pass def direct_ea_A_write8(self, opcode): pass def direct_ea_B_write8(self, opcode): pass def direct_ea_D_write16(self, opcode): pass def direct_ea_read8_write8(self, opcode): pass def direct_ea_write8(self, opcode): pass def direct_ea_A_write8(self, opcode): pass def direct_ea_S_write16(self, opcode): pass def direct_ea_U_write16(self, opcode): pass def direct_ea_X_write16(self, opcode): pass def direct_ea_Y_write16(self, opcode): pass def direct_word_D_read16(self, opcode): pass def direct_word_S_read16(self, opcode): pass def direct_word_U_read16(self, opcode): pass def direct_word_X_read16(self, opcode): pass def direct_word_Y_read16(self, opcode): pass def extended_A_read8(self, opcode): pass def extended_B_read8(self, opcode): pass def extended_read8(self, opcode): pass def extended_ea_A_write8(self, opcode): pass def extended_ea_B_write8(self, opcode): pass def extended_ea_D_write16(self, opcode): pass def extended_ea_read8_write8(self, opcode): pass def extended_ea_write8(self, opcode): pass def extended_ea_A_write8(self, opcode): pass def extended_ea_S_write16(self, opcode): pass def extended_ea_U_write16(self, opcode): pass def extended_ea_X_write16(self, opcode): pass def extended_ea_Y_write16(self, opcode): pass def extended_word_D_read16(self, opcode): pass def extended_word_S_read16(self, opcode): pass def extended_word_U_read16(self, opcode): pass def extended_word_X_read16(self, opcode): pass def extended_word_Y_read16(self, opcode): pass def immediate_A_read8(self, opcode): pass def immediate_B_read8(self, opcode): pass def immediate_CC_read8(self, opcode): pass def immediate_read8(self, opcode): pass def immediate_S_read8(self, opcode): pass def immediate_U_read8(self, opcode): pass def immediate_word_D_read16(self, opcode): pass def immediate_word_S_read16(self, opcode): pass def immediate_word_U_read16(self, opcode): pass def immediate_word_X_read16(self, opcode): pass def immediate_word_Y_read16(self, opcode): pass def indexed_A_read8(self, opcode): pass def indexed_B_read8(self, opcode): pass def indexed_read8(self, opcode): pass def indexed_ea_A_write8(self, opcode): pass def indexed_ea_B_write8(self, opcode): pass def indexed_ea_D_write16(self, opcode): pass def indexed_ea_read8_write8(self, opcode): pass def indexed_ea_write8(self, opcode): pass def indexed_ea_A_write8(self, opcode): pass def indexed_ea_S_write16(self, opcode): pass def indexed_ea_S_write16(self, opcode): pass def indexed_ea_U_write16(self, opcode): pass def indexed_ea_U_write16(self, opcode): pass def indexed_ea_X_write16(self, opcode): pass def indexed_ea_X_write16(self, opcode): pass def indexed_ea_Y_write16(self, opcode): pass def indexed_ea_Y_write16(self, opcode): pass def indexed_word_D_read16(self, opcode): pass def indexed_word_S_read16(self, opcode): pass def indexed_word_U_read16(self, opcode): pass def indexed_word_X_read16(self, opcode): pass def indexed_word_Y_read16(self, opcode): pass def inherent_A(self, opcode): pass def inherent_B(self, opcode): pass def inherent_A(self, opcode): pass def relative_ea(self, opcode): pass def relative_word_ea(self, opcode): pass
76
0
7
0
6
0
1
0
1
1
0
1
75
26
75
77
564
77
487
132
411
0
207
132
131
1
1
0
75
1,364
6809/MC6809
6809_MC6809/MC6809/components/cpu_utils/instruction_caller.py
MC6809.components.cpu_utils.instruction_caller.OpCollection
class OpCollection: def __init__(self, cpu): self.cpu = cpu self.opcode_dict = {} self.collect_ops() def get_opcode_dict(self): return self.opcode_dict def collect_ops(self): # Get the members not from class instance, so that's possible to # exclude properties without "activate" them. cls = type(self.cpu) for name, cls_method in inspect.getmembers(cls): if name.startswith("_") or isinstance(cls_method, property): continue try: opcodes = cls_method._opcodes except AttributeError: continue instr_func = getattr(self.cpu, name) self._add_ops(opcodes, instr_func) def _add_ops(self, opcodes, instr_func): # log.debug("%20s: %s" % ( # instr_func.__name__, ",".join(["$%x" % c for c in opcodes]) # )) for op_code in opcodes: assert op_code not in self.opcode_dict, \ f"Opcode ${op_code:x} ({instr_func.__name__}) defined more then one time!" op_code_data = MC6809OP_DATA_DICT[op_code] func_name = func_name_from_op_code(op_code) if self.cpu.cfg.trace: InstructionClass = InstructionTrace else: InstructionClass = PrepagedInstructions instrution_class = InstructionClass(self.cpu, instr_func) try: func = getattr(instrution_class, func_name) except AttributeError as err: raise AttributeError(f"{err} (op code: ${op_code:02x})") self.opcode_dict[op_code] = (op_code_data["cycles"], func)
class OpCollection: def __init__(self, cpu): pass def get_opcode_dict(self): pass def collect_ops(self): pass def _add_ops(self, opcodes, instr_func): pass
5
0
11
2
8
1
3
0.15
0
5
2
0
4
2
4
4
49
10
34
18
29
5
32
17
27
4
0
2
10
1,365
6809/MC6809
6809_MC6809/MC6809/components/mc6809_addressing.py
MC6809.components.mc6809_addressing.AddressingMixin
class AddressingMixin: def get_m_immediate(self): ea, m = self.read_pc_byte() # log.debug("\tget_m_immediate(): $%x from $%x", m, ea) return m def get_m_immediate_word(self): ea, m = self.read_pc_word() # log.debug("\tget_m_immediate_word(): $%x from $%x", m, ea) return m def get_ea_direct(self): op_addr, m = self.read_pc_byte() dp = self.direct_page.value ea = dp << 8 | m # log.debug("\tget_ea_direct(): ea = dp << 8 | m => $%x=$%x<<8|$%x", ea, dp, m) return ea def get_ea_m_direct(self): ea = self.get_ea_direct() m = self.memory.read_byte(ea) # log.debug("\tget_ea_m_direct(): ea=$%x m=$%x", ea, m) return ea, m def get_m_direct(self): ea = self.get_ea_direct() m = self.memory.read_byte(ea) # log.debug("\tget_m_direct(): $%x from $%x", m, ea) return m def get_m_direct_word(self): ea = self.get_ea_direct() m = self.memory.read_word(ea) # log.debug("\tget_m_direct(): $%x from $%x", m, ea) return m INDEX_POSTBYTE2STR = { 0x00: REG_X, # 16 bit index register 0x01: REG_Y, # 16 bit index register 0x02: REG_U, # 16 bit user-stack pointer 0x03: REG_S, # 16 bit system-stack pointer } def get_ea_indexed(self): """ Calculate the address for all indexed addressing modes """ addr, postbyte = self.read_pc_byte() # log.debug("\tget_ea_indexed(): postbyte: $%02x (%s) from $%04x", # postbyte, byte2bit_string(postbyte), addr # ) rr = (postbyte >> 5) & 3 try: register_str = self.INDEX_POSTBYTE2STR[rr] except KeyError: raise RuntimeError(f"Register ${rr:x} doesn't exists! (postbyte: ${postbyte:x})") register_obj = self.register_str2object[register_str] register_value = register_obj.value # log.debug("\t%02x == register %s: value $%x", # rr, register_obj.name, register_value # ) if not is_bit_set(postbyte, bit=7): # bit 7 == 0 # EA = n, R - use 5-bit offset from post-byte offset = signed5(postbyte & 0x1f) ea = register_value + offset # log.debug( # "\tget_ea_indexed(): bit 7 == 0: reg.value: $%04x -> ea=$%04x + $%02x = $%04x", # register_value, register_value, offset, ea # ) return ea addr_mode = postbyte & 0x0f self.cycles += 1 offset = None # TODO: Optimized this, maybe use a dict mapping... if addr_mode == 0x0: # log.debug("\t0000 0x0 | ,R+ | increment by 1") ea = register_value register_obj.increment(1) elif addr_mode == 0x1: # log.debug("\t0001 0x1 | ,R++ | increment by 2") ea = register_value register_obj.increment(2) self.cycles += 1 elif addr_mode == 0x2: # log.debug("\t0010 0x2 | ,R- | decrement by 1") register_obj.decrement(1) ea = register_obj.value elif addr_mode == 0x3: # log.debug("\t0011 0x3 | ,R-- | decrement by 2") register_obj.decrement(2) ea = register_obj.value self.cycles += 1 elif addr_mode == 0x4: # log.debug("\t0100 0x4 | ,R | No offset") ea = register_value elif addr_mode == 0x5: # log.debug("\t0101 0x5 | B, R | B register offset") offset = signed8(self.accu_b.value) elif addr_mode == 0x6: # log.debug("\t0110 0x6 | A, R | A register offset") offset = signed8(self.accu_a.value) elif addr_mode == 0x8: # log.debug("\t1000 0x8 | n, R | 8 bit offset") offset = signed8(self.read_pc_byte()[1]) elif addr_mode == 0x9: # log.debug("\t1001 0x9 | n, R | 16 bit offset") offset = signed16(self.read_pc_word()[1]) self.cycles += 1 elif addr_mode == 0xa: # log.debug("\t1010 0xa | illegal, set ea=0") ea = 0 elif addr_mode == 0xb: # log.debug("\t1011 0xb | D, R | D register offset") # D - 16 bit concatenated reg. (A + B) offset = signed16(self.accu_d.value) # FIXME: signed16() ok? self.cycles += 1 elif addr_mode == 0xc: # log.debug("\t1100 0xc | n, PCR | 8 bit offset from program counter") __, value = self.read_pc_byte() value_signed = signed8(value) ea = self.program_counter.value + value_signed # log.debug("\tea = pc($%x) + $%x = $%x (dez.: %i + %i = %i)", # self.program_counter, value_signed, ea, # self.program_counter, value_signed, ea, # ) elif addr_mode == 0xd: # log.debug("\t1101 0xd | n, PCR | 16 bit offset from program counter") __, value = self.read_pc_word() value_signed = signed16(value) ea = self.program_counter.value + value_signed self.cycles += 1 # log.debug("\tea = pc($%x) + $%x = $%x (dez.: %i + %i = %i)", # self.program_counter, value_signed, ea, # self.program_counter, value_signed, ea, # ) elif addr_mode == 0xe: # log.error("\tget_ea_indexed(): illegal address mode, use 0xffff") ea = 0xffff # illegal elif addr_mode == 0xf: # log.debug("\t1111 0xf | [n] | 16 bit address - extended indirect") __, ea = self.read_pc_word() else: raise RuntimeError(f"Illegal indexed addressing mode: ${addr_mode:x}") if offset is not None: ea = register_value + offset # log.debug("\t$%x + $%x = $%x (dez: %i + %i = %i)", # register_value, offset, ea, # register_value, offset, ea # ) ea = ea & 0xffff if is_bit_set(postbyte, bit=4): # bit 4 is 1 -> Indirect # log.debug("\tIndirect addressing: get new ea from $%x", ea) ea = self.memory.read_word(ea) # log.debug("\tIndirect addressing: new ea is $%x", ea) # log.debug("\tget_ea_indexed(): return ea=$%x", ea) return ea def get_m_indexed(self): ea = self.get_ea_indexed() m = self.memory.read_byte(ea) # log.debug("\tget_m_indexed(): $%x from $%x", m, ea) return m def get_ea_m_indexed(self): ea = self.get_ea_indexed() m = self.memory.read_byte(ea) # log.debug("\tget_ea_m_indexed(): ea = $%x m = $%x", ea, m) return ea, m def get_m_indexed_word(self): ea = self.get_ea_indexed() m = self.memory.read_word(ea) # log.debug("\tget_m_indexed_word(): $%x from $%x", m, ea) return m def get_ea_extended(self): """ extended indirect addressing mode takes a 2-byte value from post-bytes """ attr, ea = self.read_pc_word() # log.debug("\tget_ea_extended() ea=$%x from $%x", ea, attr) return ea def get_m_extended(self): ea = self.get_ea_extended() m = self.memory.read_byte(ea) # log.debug("\tget_m_extended(): $%x from $%x", m, ea) return m def get_ea_m_extended(self): ea = self.get_ea_extended() m = self.memory.read_byte(ea) # log.debug("\tget_m_extended(): ea = $%x m = $%x", ea, m) return ea, m def get_m_extended_word(self): ea = self.get_ea_extended() m = self.memory.read_word(ea) # log.debug("\tget_m_extended_word(): $%x from $%x", m, ea) return m def get_ea_relative(self): addr, x = self.read_pc_byte() x = signed8(x) ea = self.program_counter.value + x # log.debug("\tget_ea_relative(): ea = $%x + %i = $%x \t| %s", # self.program_counter, x, ea, # self.cfg.mem_info.get_shortest(ea) # ) return ea def get_ea_relative_word(self): addr, x = self.read_pc_word() ea = self.program_counter.value + x # log.debug("\tget_ea_relative_word(): ea = $%x + %i = $%x \t| %s", # self.program_counter, x, ea, # self.cfg.mem_info.get_shortest(ea) # ) return ea
class AddressingMixin: def get_m_immediate(self): pass def get_m_immediate_word(self): pass def get_ea_direct(self): pass def get_ea_m_direct(self): pass def get_m_direct(self): pass def get_m_direct_word(self): pass def get_ea_indexed(self): ''' Calculate the address for all indexed addressing modes ''' pass def get_m_indexed(self): pass def get_ea_m_indexed(self): pass def get_m_indexed_word(self): pass def get_ea_extended(self): ''' extended indirect addressing mode takes a 2-byte value from post-bytes ''' pass def get_m_extended(self): pass def get_ea_m_extended(self): pass def get_m_extended_word(self): pass def get_ea_relative(self): pass def get_ea_relative_word(self): pass
17
2
13
1
8
5
2
0.59
0
2
0
1
16
0
16
16
228
25
133
56
116
78
113
56
96
20
0
1
35
1,366
6809/MC6809
6809_MC6809/MC6809/components/mc6809_cc_register.py
MC6809.components.mc6809_cc_register.CPUConditionCodeRegisterMixin
class CPUConditionCodeRegisterMixin: """ CC - 8 bit condition code register bits """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.E = 0 # E - 0x80 - bit 7 - Entire register state stacked self.F = 0 # F - 0x40 - bit 6 - FIRQ interrupt masked self.H = 0 # H - 0x20 - bit 5 - Half-Carry self.I = 0 # I - 0x10 - bit 4 - IRQ interrupt masked self.N = 0 # N - 0x08 - bit 3 - Negative result (twos complement) self.Z = 0 # Z - 0x04 - bit 2 - Zero result self.V = 0 # V - 0x02 - bit 1 - Overflow self.C = 0 # C - 0x01 - bit 0 - Carry (or borrow) self.cc_register = ConditionCodeRegister(self) #### def get_cc_value(self): return self.C | \ self.V << 1 | \ self.Z << 2 | \ self.N << 3 | \ self.I << 4 | \ self.H << 5 | \ self.F << 6 | \ self.E << 7 def set_cc(self, status): self.E, self.F, self.H, self.I, self.N, self.Z, self.V, self.C = ( 0 if status & x == 0 else 1 for x in (128, 64, 32, 16, 8, 4, 2, 1) ) def get_cc_info(self): """ return cc flags as text representation, like: 'E.H....C' used in trace mode and unittests """ return cc_value2txt(self.get_cc_value()) #### def set_H(self, a, b, r): if not self.H and (a ^ b ^ r) & 0x10: self.H = 1 # log.debug("\tset_H(): set half-carry flag to %i: ($%02x ^ $%02x ^ $%02x) & 0x10 = $%02x", # self.H, a, b, r, r2 # ) # else: # log.debug("\rset_H(): leave old value 1") def set_Z8(self, r): if self.Z == 0: r2 = r & 0xff self.Z = 1 if r2 == 0 else 0 # log.debug("\tset_Z8(): set zero flag to %i: $%02x & 0xff = $%02x", # self.Z, r, r2 # ) # else: # log.debug("\tset_Z8(): leave old value 1") def set_Z16(self, r): if not self.Z and not r & 0xffff: self.Z = 1 # log.debug("\tset_Z16(): set zero flag to %i: $%04x & 0xffff = $%04x", # self.Z, r, r2 # ) # else: # log.debug("\tset_Z16(): leave old value 1") def set_N8(self, r): if not self.N and r & 0x80: self.N = 1 # log.debug("\tset_N8(): set negative flag to %i: ($%02x & 0x80) = $%02x", # self.N, r, r2 # ) # else: # log.debug("\tset_N8(): leave old value 1") def set_N16(self, r): if not self.N and r & 0x8000: self.N = 1 # log.debug("\tset_N16(): set negative flag to %i: ($%04x & 0x8000) = $%04x", # self.N, r, r2 # ) # else: # log.debug("\tset_N16(): leave old value 1") def set_C8(self, r): if not self.C and r & 0x100: self.C = 1 # log.debug("\tset_C8(): carry flag to %i: ($%02x & 0x100) = $%02x", # self.C, r, r2 # ) # else: # log.debug("\tset_C8(): leave old value 1") def set_C16(self, r): if not self.C and r & 0x10000: self.C = 1 # log.debug("\tset_C16(): carry flag to %i: ($%04x & 0x10000) = $%04x", # self.C, r, r2 # ) # else: # log.debug("\tset_C16(): leave old value 1") def set_V8(self, a, b, r): if not self.V and (a ^ b ^ r ^ (r >> 1)) & 0x80: self.V = 1 # log.debug("\tset_V8(): overflow flag to %i: (($%02x ^ $%02x ^ $%02x ^ ($%02x >> 1)) & 0x80) = $%02x", # self.V, a, b, r, r, r2 # ) # else: # log.debug("\tset_V8(): leave old value 1") def set_V16(self, a, b, r): if not self.V and (a ^ b ^ r ^ (r >> 1)) & 0x8000: self.V = 1 # log.debug("\tset_V16(): overflow flag to %i: (($%04x ^ $%04x ^ $%04x ^ ($%04x >> 1)) & 0x8000) = $%04x", # self.V, a, b, r, r, r2 # ) # else: # log.debug("\tset_V16(): leave old value 1") #### def clear_NZ(self): # log.debug("\tclear_NZ()") self.N = 0 self.Z = 0 def clear_NZC(self): # log.debug("\tclear_NZC()") self.N = 0 self.Z = 0 self.C = 0 def clear_NZV(self): # log.debug("\tclear_NZV()") self.N = 0 self.Z = 0 self.V = 0 def clear_NZVC(self): # log.debug("\tclear_NZVC()") self.N = 0 self.Z = 0 self.V = 0 self.C = 0 def clear_HNZVC(self): # log.debug("\tclear_HNZVC()") self.H = 0 self.N = 0 self.Z = 0 self.V = 0 self.C = 0 #### def update_NZ_8(self, r): self.set_N8(r) self.set_Z8(r) def update_0100(self): """ CC bits "HNZVC": -0100 """ self.N = 0 self.Z = 1 self.V = 0 self.C = 0 def update_NZ01_8(self, r): self.set_N8(r) self.set_Z8(r) self.V = 0 self.C = 1 def update_NZ_16(self, r): self.set_N16(r) self.set_Z16(r) def update_NZ0_8(self, r): self.set_N8(r) self.set_Z8(r) self.V = 0 def update_NZ0_16(self, r): self.set_N16(r) self.set_Z16(r) self.V = 0 def update_NZC_8(self, r): self.set_N8(r) self.set_Z8(r) self.set_C8(r) def update_NZVC_8(self, a, b, r): self.set_N8(r) self.set_Z8(r) self.set_V8(a, b, r) self.set_C8(r) def update_NZVC_16(self, a, b, r): self.set_N16(r) self.set_Z16(r) self.set_V16(a, b, r) self.set_C16(r) def update_HNZVC_8(self, a, b, r): self.set_H(a, b, r) self.set_N8(r) self.set_Z8(r) self.set_V8(a, b, r) self.set_C8(r)
class CPUConditionCodeRegisterMixin: ''' CC - 8 bit condition code register bits ''' def __init__(self, *args, **kwargs): pass def get_cc_value(self): pass def set_cc(self, status): pass def get_cc_info(self): ''' return cc flags as text representation, like: 'E.H....C' used in trace mode and unittests ''' pass def set_H(self, a, b, r): pass def set_Z8(self, r): pass def set_Z16(self, r): pass def set_N8(self, r): pass def set_N16(self, r): pass def set_C8(self, r): pass def set_C16(self, r): pass def set_V8(self, a, b, r): pass def set_V16(self, a, b, r): pass def clear_NZ(self): pass def clear_NZC(self): pass def clear_NZV(self): pass def clear_NZVC(self): pass def clear_HNZVC(self): pass def update_NZ_8(self, r): pass def update_0100(self): ''' CC bits "HNZVC": -0100 ''' pass def update_NZ01_8(self, r): pass def update_NZ_16(self, r): pass def update_NZ0_8(self, r): pass def update_NZ0_16(self, r): pass def update_NZC_8(self, r): pass def update_NZVC_8(self, a, b, r): pass def update_NZVC_16(self, a, b, r): pass def update_HNZVC_8(self, a, b, r): pass
29
3
5
0
4
1
1
0.56
0
2
1
1
28
9
28
28
214
33
121
39
92
68
112
39
83
3
0
1
39
1,367
6809/MC6809
6809_MC6809/MC6809/components/mc6809_cc_register.py
MC6809.components.mc6809_cc_register.ConditionCodeRegister
class ConditionCodeRegister: """ Imitate the normal register API """ name = "CC" WIDTH = 8 # 8 Bit def __init__(self, cpu): self.get_cc_value = cpu.get_cc_value self.set_cc = cpu.set_cc @property def value(self): return self.get_cc_value() def set(self, status): return self.set_cc(status)
class ConditionCodeRegister: ''' Imitate the normal register API ''' def __init__(self, cpu): pass @property def value(self): pass def set(self, status): pass
5
1
2
0
2
0
1
0.36
0
0
0
0
3
2
3
3
17
3
11
9
6
4
10
8
6
1
0
0
3
1,368
6809/MC6809
6809_MC6809/MC6809/core/cpu_control_server.py
MC6809.core.cpu_control_server.ControlHandlerFactory
class ControlHandlerFactory: def __init__(self, cpu): self.cpu = cpu def __call__(self, request, client_address, server): return ControlHandler(request, client_address, server, self.cpu)
class ControlHandlerFactory: def __init__(self, cpu): pass def __call__(self, request, client_address, server): pass
3
0
2
0
2
0
1
0
0
1
1
0
2
1
2
2
6
1
5
4
2
0
5
4
2
1
0
0
2
1,369
6809/MC6809
6809_MC6809/MC6809/components/mc6809_speedlimited.py
MC6809.components.mc6809_speedlimited.CPUSpeedLimitMixin
class CPUSpeedLimitMixin: max_delay = 0.01 # maximum time.sleep() value per burst run delay = 0 # the current time.sleep() value per burst run def delayed_burst_run(self, target_cycles_per_sec): """ Run CPU not faster than given speedlimit """ old_cycles = self.cycles start_time = time.time() self.burst_run() is_duration = time.time() - start_time new_cycles = self.cycles - old_cycles try: is_cycles_per_sec = new_cycles / is_duration except ZeroDivisionError: pass else: should_burst_duration = is_cycles_per_sec / target_cycles_per_sec target_duration = should_burst_duration * is_duration delay = target_duration - is_duration if delay > 0: if delay > self.max_delay: self.delay = self.max_delay else: self.delay = delay time.sleep(self.delay) self.call_sync_callbacks()
class CPUSpeedLimitMixin: def delayed_burst_run(self, target_cycles_per_sec): ''' Run CPU not faster than given speedlimit ''' pass
2
1
25
3
21
1
4
0.13
0
1
0
1
1
0
1
1
29
4
24
12
22
3
23
12
21
4
0
3
4
1,370
6809/MC6809
6809_MC6809/MC6809/components/mc6809_tools.py
MC6809.components.mc6809_tools.CPUThreadedStatusMixin
class CPUThreadedStatusMixin: def __init__(self, *args, **kwargs): cpu_status_queue = kwargs.get("cpu_status_queue", None) if cpu_status_queue is not None: status_thread = CPUStatusThread(self, cpu_status_queue) status_thread.deamon = True status_thread.start()
class CPUThreadedStatusMixin: def __init__(self, *args, **kwargs): pass
2
0
6
0
6
0
2
0
0
1
1
1
1
0
1
1
7
0
7
4
5
0
7
4
5
2
0
1
2
1,371
6809/MC6809
6809_MC6809/MC6809/components/mc6809_tools.py
MC6809.components.mc6809_tools.CPUTypeAssertMixin
class CPUTypeAssertMixin: """ assert that all attributes of the CPU class will remain as the same. We use no property, because it's slower. But without it, it's hard to find if somewhere not .set() or .incement() is used. With this helper a error will raise, if the type of a attribute will be changed, e.g.: cpu.index_x = ValueStorage16Bit(...) cpu.index_x = 0x1234 # will raised a error """ __ATTR_DICT = {} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__set_attr_dict() warnings.warn( "CPU TypeAssert used! (Should be only activated for debugging!)", stacklevel=2, ) def __set_attr_dict(self): for name, obj in inspect.getmembers(self, lambda x: not (inspect.isroutine(x))): if name.startswith("_") or name == "cfg": continue self.__ATTR_DICT[name] = type(obj) def __setattr__(self, attr, value): if attr in self.__ATTR_DICT: obj = self.__ATTR_DICT[attr] assert isinstance(value, obj), \ f"Attribute {attr!r} is no more type {obj} (Is now: {type(obj)})!" return object.__setattr__(self, attr, value)
class CPUTypeAssertMixin: ''' assert that all attributes of the CPU class will remain as the same. We use no property, because it's slower. But without it, it's hard to find if somewhere not .set() or .incement() is used. With this helper a error will raise, if the type of a attribute will be changed, e.g.: cpu.index_x = ValueStorage16Bit(...) cpu.index_x = 0x1234 # will raised a error ''' def __init__(self, *args, **kwargs): pass def __set_attr_dict(self): pass def __setattr__(self, attr, value): pass
4
1
6
0
6
0
2
0.45
0
3
0
1
3
0
3
3
34
5
20
7
16
9
16
7
12
3
0
2
6
1,372
6809/MC6809
6809_MC6809/MC6809/components/memory.py
MC6809.components.memory.Memory
class Memory: def __init__(self, cfg, read_bus_request_queue=None, read_bus_response_queue=None, write_bus_queue=None): self.cfg = cfg self.read_bus_request_queue = read_bus_request_queue self.read_bus_response_queue = read_bus_response_queue self.write_bus_queue = write_bus_queue self.INTERNAL_SIZE = (0xFFFF + 1) self.RAM_SIZE = (self.cfg.RAM_END - self.cfg.RAM_START) + 1 self.ROM_SIZE = (self.cfg.ROM_END - self.cfg.ROM_START) + 1 assert not hasattr(cfg, "RAM_SIZE"), ( f"cfg.RAM_SIZE is deprecated! Remove it from: {self.cfg.__class__.__name__}" ) assert not hasattr(cfg, "ROM_SIZE"), ( f"cfg.ROM_SIZE is deprecated! Remove it from: {self.cfg.__class__.__name__}" ) assert not hasattr(cfg, "ram"), ( f"cfg.ram is deprecated! Remove it from: {self.cfg.__class__.__name__}" ) assert not hasattr(cfg, "DEFAULT_ROM"), ( f"cfg.DEFAULT_ROM must be converted" f" to DEFAULT_ROMS tuple in {self.cfg.__class__.__name__}" ) assert self.RAM_SIZE + self.RAM_SIZE <= self.INTERNAL_SIZE, ( f"{self.RAM_SIZE + self.RAM_SIZE} Bytes < {self.INTERNAL_SIZE} Bytes" ) # About different types of memory see: # http://www.python-forum.de/viewtopic.php?p=263775#p263775 (de) # The old variant: Use a simple List: # self._mem = [None] * self.cfg.MEMORY_SIZE # Bytearray will be consume less RAM, but it's slower: # self._mem = bytearray(self.cfg.MEMORY_SIZE) # array consumes also less RAM than lists and it's a little bit faster: self._mem = array.array("B", [0x00] * self.INTERNAL_SIZE) # unsigned char if cfg and cfg.rom_cfg: for romfile in cfg.rom_cfg: self.load_file(romfile) self._read_byte_callbacks = {} self._read_word_callbacks = {} self._write_byte_callbacks = {} self._write_word_callbacks = {} # Memory middlewares are function that called on memory read or write # the function can change the value that is read/write # # init read/write byte middlewares: self._read_byte_middleware = {} self._write_byte_middleware = {} for addr_range, functions in list(cfg.memory_byte_middlewares.items()): start_addr, end_addr = addr_range read_func, write_func = functions if read_func: self.add_read_byte_middleware(read_func, start_addr, end_addr) if write_func: self.add_write_byte_middleware(write_func, start_addr, end_addr) # init read/write word middlewares: self._read_word_middleware = {} self._write_word_middleware = {} for addr_range, functions in list(cfg.memory_word_middlewares.items()): start_addr, end_addr = addr_range read_func, write_func = functions if read_func: self.add_read_word_middleware(read_func, start_addr, end_addr) if write_func: self.add_write_word_middleware(write_func, start_addr, end_addr) # log.critical( # # log.debug( # "memory read middlewares: %s", self._read_byte_middleware # ) # log.critical( # # log.debug( # "memory write middlewares: %s", self._write_byte_middleware # ) log.critical("init RAM $%04x (dez.:%s) Bytes RAM $%04x (dez.:%s) Bytes (total %s real: %s)", self.RAM_SIZE, self.RAM_SIZE, self.ROM_SIZE, self.ROM_SIZE, self.RAM_SIZE + self.ROM_SIZE, len(self._mem) ) # --------------------------------------------------------------------------- def _map_address_range(self, callbacks_dict, callback_func, start_addr, end_addr=None): if end_addr is None: callbacks_dict[start_addr] = callback_func else: for addr in range(start_addr, end_addr + 1): callbacks_dict[addr] = callback_func # --------------------------------------------------------------------------- def add_read_byte_callback(self, callback_func, start_addr, end_addr=None): self._map_address_range(self._read_byte_callbacks, callback_func, start_addr, end_addr) def add_read_word_callback(self, callback_func, start_addr, end_addr=None): self._map_address_range(self._read_word_callbacks, callback_func, start_addr, end_addr) def add_write_byte_callback(self, callback_func, start_addr, end_addr=None): self._map_address_range(self._write_byte_callbacks, callback_func, start_addr, end_addr) def add_write_word_callback(self, callback_func, start_addr, end_addr=None): self._map_address_range(self._write_word_callbacks, callback_func, start_addr, end_addr) # --------------------------------------------------------------------------- def add_read_byte_middleware(self, callback_func, start_addr, end_addr=None): self._map_address_range(self._read_byte_middleware, callback_func, start_addr, end_addr) def add_write_byte_middleware(self, callback_func, start_addr, end_addr=None): self._map_address_range(self._write_byte_middleware, callback_func, start_addr, end_addr) def add_read_word_middleware(self, callback_func, start_addr, end_addr=None): self._map_address_range(self._read_word_middleware, callback_func, start_addr, end_addr) def add_write_word_middleware(self, callback_func, start_addr, end_addr=None): self._map_address_range(self._write_word_middleware, callback_func, start_addr, end_addr) # --------------------------------------------------------------------------- def load(self, address, data): if isinstance(data, str): data = [ord(c) for c in data] log.debug("ROM load at $%04x: %s", address, ", ".join(f"${i:02x}" for i in data) ) for ea, datum in enumerate(data, address): try: self._mem[ea] = datum except OverflowError as err: raise OverflowError( f"{err} - datum=${datum:x} ea=${ea:04x}" f" (load address was: ${address:04x} - data length: {len(data):d}Bytes)" ) def load_file(self, romfile): data = romfile.get_data() self.load(romfile.address, data) log.critical("Load ROM file %r to $%04x", romfile.filepath, romfile.address) # --------------------------------------------------------------------------- def read_byte(self, address): self.cpu.cycles += 1 if address in self._read_byte_callbacks: byte = self._read_byte_callbacks[address]( self.cpu.cycles, self.cpu.last_op_address, address ) assert byte is not None, ( f"Error: read byte callback for ${address:04x}" f" func {self._read_byte_callbacks[address].__name__!r} has return None!" ) return byte try: byte = self._mem[address] except KeyError: msg = f"reading outside memory area (PC:${self.cpu.program_counter.value:x})" self.cfg.mem_info(address, msg) msg2 = f"{msg}: ${address:x}" log.warning(msg2) # raise RuntimeError(msg2) byte = 0x0 if address in self._read_byte_middleware: byte = self._read_byte_middleware[address]( self.cpu.cycles, self.cpu.last_op_address, address, byte ) assert byte is not None, ( f"Error: read byte middleware for ${address:04x}" f" func {self._read_byte_middleware[address].__name__!r} has return None!" ) # log.log(5, "%04x| (%i) read byte $%x from $%x", # self.cpu.last_op_address, self.cpu.cycles, # byte, address # ) return byte def read_word(self, address): if address in self._read_word_callbacks: word = self._read_word_callbacks[address]( self.cpu.cycles, self.cpu.last_op_address, address ) assert word is not None, ( f"Error: read word callback for ${address:04x}" f" func {self._read_word_callbacks[address].__name__!r} has return None!" ) return word # 6809 is Big-Endian return (self.read_byte(address) << 8) + self.read_byte(address + 1) # --------------------------------------------------------------------------- def write_byte(self, address, value): self.cpu.cycles += 1 assert value >= 0, f"Write negative byte hex:{value:00x} dez:{value:d} to ${address:04x}" assert value <= 0xff, ( f"Write out of range byte hex:{value:02x} dez:{value:d} to ${address:04x}" ) # if not (0x0 <= value <= 0xff): # log.error("Write out of range value $%02x to $%04x", value, address) # value = value & 0xff # log.error(" ^^^^ wrap around to $%x", value) if address in self._write_byte_middleware: value = self._write_byte_middleware[address]( self.cpu.cycles, self.cpu.last_op_address, address, value ) assert value is not None, ( f"Error: write byte middleware for ${address:04x}" f" func {self._write_byte_middleware[address].__name__!r} has return None!" ) if address in self._write_byte_callbacks: return self._write_byte_callbacks[address]( self.cpu.cycles, self.cpu.last_op_address, address, value ) if self.cfg.ROM_START <= address <= self.cfg.ROM_END: msg = ( f"{self.cpu.program_counter.value:04x}|" f" writing into ROM at ${address:04x} ignored." ) self.cfg.mem_info(address, msg) msg2 = f"{msg}: ${address:x}" log.critical(msg2) return try: self._mem[address] = value except (IndexError, KeyError): msg = ( f"{self.cpu.program_counter.value:04x}|" f" writing to {address:x} is outside RAM/ROM !" ) self.cfg.mem_info(address, msg) msg2 = f"{msg}: ${address:x}" log.warning(msg2) # raise RuntimeError(msg2) def write_word(self, address, word): assert word >= 0, f"Write negative word hex:{word:04x} dez:{word:d} to ${address:04x}" assert word <= 0xffff, ( f"Write out of range word hex:{word:04x} dez:{word:d} to ${address:04x}" ) if address in self._write_word_middleware: word = self._write_word_middleware[address]( self.cpu.cycles, self.cpu.last_op_address, address, word ) assert word is not None, ( f"Error: write word middleware for ${address:04x}" f" func {self._write_word_middleware[address].__name__!r} has return None!" ) if address in self._write_word_callbacks: return self._write_word_callbacks[address]( self.cpu.cycles, self.cpu.last_op_address, address, word ) # 6809 is Big-Endian self.write_byte(address, word >> 8) self.write_byte(address + 1, word & 0xff) # --------------------------------------------------------------------------- def get(self, start, end): """ used in unittests """ return [self.read_byte(addr) for addr in range(start, end)] def iter_bytes(self, start, end): for addr in range(start, end): yield addr, self.read_byte(addr) def get_dump(self, start, end): dump_lines = [] for addr, value in self.iter_bytes(start, end): msg = f"${addr:04x}: ${value:02x} (dez: {value:d})" msg = f"{msg:<25}| {self.cfg.mem_info.get_shortest(addr)}" dump_lines.append(msg) return dump_lines def print_dump(self, start, end): print(f"Memory dump from ${start:04x} to ${end:04x}:") dump_lines = self.get_dump(start, end) print("\n".join(f"\t{line}" for line in dump_lines))
class Memory: def __init__(self, cfg, read_bus_request_queue=None, read_bus_response_queue=None, write_bus_queue=None): pass def _map_address_range(self, callbacks_dict, callback_func, start_addr, end_addr=None): pass def add_read_byte_callback(self, callback_func, start_addr, end_addr=None): pass def add_read_word_callback(self, callback_func, start_addr, end_addr=None): pass def add_write_byte_callback(self, callback_func, start_addr, end_addr=None): pass def add_write_word_callback(self, callback_func, start_addr, end_addr=None): pass def add_read_byte_middleware(self, callback_func, start_addr, end_addr=None): pass def add_write_byte_middleware(self, callback_func, start_addr, end_addr=None): pass def add_read_word_middleware(self, callback_func, start_addr, end_addr=None): pass def add_write_word_middleware(self, callback_func, start_addr, end_addr=None): pass def load(self, address, data): pass def load_file(self, romfile): pass def read_byte(self, address): pass def read_word(self, address): pass def write_byte(self, address, value): pass def write_word(self, address, word): pass def get(self, start, end): ''' used in unittests ''' pass def iter_bytes(self, start, end): pass def get_dump(self, start, end): pass def print_dump(self, start, end): pass
21
1
14
2
10
2
2
0.21
0
8
0
0
20
16
20
20
309
59
208
56
187
43
147
55
126
9
0
2
45
1,373
6809/MC6809
6809_MC6809/MC6809/core/bechmark.py
MC6809.core.bechmark.Test6809_Program2
class Test6809_Program2(Test6809_Program): def runTest(self): pass def bench(self, loops, multiply, func, msg): print(f"\n{msg} benchmark") self.setUp() self.cpu.cycles = 0 txt = string.printable txt = bytes(txt, encoding="UTF-8") txt = txt * multiply print(f"\nStart {loops:d} {msg} loops with {len(txt):d} Bytes test string...") start_time = time.time() for __ in range(loops): self._crc32(txt) duration = time.time() - start_time print(f"{msg} benchmark runs {locale_format_number(self.cpu.cycles)} CPU cycles in {duration:.2f} sec") return duration, self.cpu.cycles def crc32_benchmark(self, loops, multiply): return self.bench(loops, multiply, self._crc32, "CRC32") def crc16_benchmark(self, loops, multiply): return self.bench(loops, multiply, self._crc16, "CRC16")
class Test6809_Program2(Test6809_Program): def runTest(self): pass def bench(self, loops, multiply, func, msg): pass def crc32_benchmark(self, loops, multiply): pass def crc16_benchmark(self, loops, multiply): pass
5
0
7
2
5
0
1
0
1
2
0
0
4
0
4
99
30
9
21
9
16
0
21
9
16
2
6
1
5
1,374
6809/MC6809
6809_MC6809/MC6809/core/configs.py
MC6809.core.configs.AddressAreas
class AddressAreas(dict): """ Hold information about memory address areas which accessed via bus. e.g.: Interrupt vectors Text screen Serial/parallel devices """ def __init__(self, areas): super().__init__() for start_addr, end_addr, txt in areas: self.add_area(start_addr, end_addr, txt) def add_area(self, start_addr, end_addr, txt): for addr in range(start_addr, end_addr + 1): dict.__setitem__(self, addr, txt)
class AddressAreas(dict): ''' Hold information about memory address areas which accessed via bus. e.g.: Interrupt vectors Text screen Serial/parallel devices ''' def __init__(self, areas): pass def add_area(self, start_addr, end_addr, txt): pass
3
1
4
0
4
0
2
0.88
1
2
0
0
2
0
2
29
17
2
8
5
5
7
8
5
5
2
2
1
4
1,375
6809/MC6809
6809_MC6809/MC6809/core/configs.py
MC6809.core.configs.BaseConfig
class BaseConfig: # # http address/port number for the CPU control server # CPU_CONTROL_ADDR = "127.0.0.1" # CPU_CONTROL_PORT = 6809 # How many ops should be execute before make a control server update cycle? BURST_COUNT = 10000 DEFAULT_ROMS = {} def __init__(self, cfg_dict): self.cfg_dict = cfg_dict self.cfg_dict["cfg_module"] = self.__module__ # FIXME: ! log.debug("cfg_dict: %s", repr(cfg_dict)) # # socket address for internal bus I/O: # if cfg_dict["bus_socket_host"] and cfg_dict["bus_socket_port"]: # self.bus = True # self.bus_socket_host = cfg_dict["bus_socket_host"] # self.bus_socket_port = cfg_dict["bus_socket_port"] # else: # self.bus = None # Will be set in cpu6809.start_CPU() assert not hasattr( cfg_dict, "ram"), f"cfg_dict.ram is deprecated! Remove it from: {self.cfg_dict.__class__.__name__}" # if cfg_dict["rom"]: # raw_rom_cfg = cfg_dict["rom"] # raise NotImplementedError("TODO: create rom cfg!") # else: self.rom_cfg = self.DEFAULT_ROMS if cfg_dict["trace"]: self.trace = True else: self.trace = False self.verbosity = cfg_dict["verbosity"] self.mem_info = DummyMemInfo() self.memory_byte_middlewares = {} self.memory_word_middlewares = {} def _get_initial_Memory(self, size): return [0x00] * size def get_initial_RAM(self): return self._get_initial_Memory(self.RAM_SIZE) def get_initial_ROM(self): return self._get_initial_Memory(self.ROM_SIZE) # def get_initial_ROM(self): # start=cfg.ROM_START, size=cfg.ROM_SIZE # self.start = start # self.end = start + size # self._mem = [0x00] * size def print_debug_info(self): print(f"Config: '{self.__class__.__name__}'") for name, value in inspect.getmembers(self): # , inspect.isdatadescriptor): if name.startswith("_"): continue # print name, type(value) if not isinstance(value, (int, str, list, tuple, dict)): continue if isinstance(value, int): print(f"{name:>20} = {value:<6} in hex: {hex(value):>7}") else: print(f"{name:>20} = {value}")
class BaseConfig: def __init__(self, cfg_dict): pass def _get_initial_Memory(self, size): pass def get_initial_RAM(self): pass def get_initial_ROM(self): pass def print_debug_info(self): pass
6
0
10
2
6
3
2
0.66
0
6
1
2
5
7
5
5
72
16
35
16
29
23
32
16
26
5
0
2
10
1,376
6809/MC6809
6809_MC6809/MC6809/core/cpu_control_server.py
MC6809.core.cpu_control_server.CPUControlServerMixin
class CPUControlServerMixin: def __init__(self, *args, **kwargs): control_handler = ControlHandlerFactory(self) server_address = (self.cfg.CPU_CONTROL_ADDR, self.cfg.CPU_CONTROL_PORT) try: control_server = HTTPServer(server_address, control_handler) except BaseException: self.running = False raise url = "http://%s:%s" % server_address log.error("Start http control server on: %s", url) control_server_thread(self, self.cfg, control_server)
class CPUControlServerMixin: def __init__(self, *args, **kwargs): pass
2
0
12
1
11
0
2
0
0
3
1
1
1
1
1
1
13
1
12
7
10
0
12
7
10
2
0
1
2
1,377
6809/MC6809
6809_MC6809/MC6809/components/mc6809_tools.py
MC6809.components.mc6809_tools.CPUStatusThread
class CPUStatusThread(threading.Thread): """ Send cycles/sec information via cpu_status_queue to the GUi main thread. Just ignore if the cpu_status_queue is full. """ def __init__(self, cpu, cpu_status_queue): super().__init__(name="CPU-Status-Thread") self.cpu = cpu self.cpu_status_queue = cpu_status_queue self.last_cpu_cycles = None self.last_cpu_cycle_update = time.time() def _run(self): while self.cpu.running: try: self.cpu_status_queue.put(self.cpu.cycles, block=False) except queue.Full: # log.critical("Can't put CPU status: Queue is full.") pass time.sleep(0.5) def run(self): try: self._run() except BaseException: self.cpu.running = False _thread.interrupt_main() raise
class CPUStatusThread(threading.Thread): ''' Send cycles/sec information via cpu_status_queue to the GUi main thread. Just ignore if the cpu_status_queue is full. ''' def __init__(self, cpu, cpu_status_queue): pass def _run(self): pass def run(self): pass
4
1
7
0
7
0
2
0.24
1
3
0
0
3
4
3
28
30
4
21
8
17
5
21
8
17
3
1
2
6
1,378
6809/MC6809
6809_MC6809/MC6809/tests/test_6809_register_changes.py
MC6809.tests.test_6809_register_changes.Test6809_EXG
class Test6809_EXG(BaseCPUTestCase): def test_EXG_A_B(self): self.cpu.accu_a.set(0xab) self.cpu.accu_b.set(0x12) self.cpu_test_run(start=0x2000, end=None, mem=[ 0x1E, 0x89, # EXG A,B ]) self.assertEqualHexByte(self.cpu.accu_a.value, 0x12) self.assertEqualHexByte(self.cpu.accu_b.value, 0xab) def test_EXG_X_Y(self): self.cpu_test_run(start=0x2000, end=None, mem=[ 0x8E, 0xAB, 0xCD, # LDX #$abcd ; set X to $abcd 0x10, 0x8E, 0x80, 0x4F, # LDY #$804f ; set Y to $804f 0x1E, 0x12, # EXG X,Y ; y,x=x,y 0x9F, 0x20, # STX $20 ; store X to $20 0x10, 0x9F, 0x40, # STY $40 ; store Y to $40 ]) self.assertEqualHexWord(self.cpu.memory.read_word(0x20), 0x804f) # X self.assertEqualHexWord(self.cpu.memory.read_word(0x40), 0xabcd) # Y def test_EXG_A_X(self): """ exange 8 bit register with a 16 bit register TODO: verify this behaviour on real hardware! """ self.cpu_test_run(start=0x2000, end=None, mem=[ 0x86, 0x56, # LDA #$56 0x8E, 0x12, 0x34, # LDX #$1234 0x1E, 0x81, # EXG A,X ]) self.assertEqualHexByte(self.cpu.accu_a.value, 0x34) self.assertEqualHexWord(self.cpu.index_x.value, 0xff56) def test_EXG_A_CC(self): """ TODO: verify this behaviour on real hardware! """ self.cpu.accu_a.set(0x1f) self.cpu.set_cc(0xe2) self.cpu_test_run(start=0x2000, end=None, mem=[ 0x1E, 0x8A, # EXG A,CC ]) self.assertEqualHexByte(self.cpu.accu_a.value, 0xe2) self.assertEqualHexByte(self.cpu.get_cc_value(), 0x1f) def test_EXG_X_CC(self): """ TODO: verify this behaviour on real hardware! """ self.cpu.index_x.set(0x1234) self.cpu.set_cc(0x56) self.cpu_test_run(start=0x2000, end=None, mem=[ 0x1E, 0x1A, # EXG X,CC ]) self.assertEqualHexWord(self.cpu.index_x.value, 0xff56) self.assertEqualHexByte(self.cpu.get_cc_value(), 0x34) def test_EXG_undefined_to_X(self): """ TODO: verify this behaviour on real hardware! """ self.cpu.index_x.set(0x1234) self.cpu_test_run(start=0x2000, end=None, mem=[ 0x1E, 0xd1, # EXG undefined,X ]) self.assertEqualHexWord(self.cpu.index_x.value, 0xffff)
class Test6809_EXG(BaseCPUTestCase): def test_EXG_A_B(self): pass def test_EXG_X_Y(self): pass def test_EXG_A_X(self): ''' exange 8 bit register with a 16 bit register TODO: verify this behaviour on real hardware! ''' pass def test_EXG_A_CC(self): ''' TODO: verify this behaviour on real hardware! ''' pass def test_EXG_X_CC(self): ''' TODO: verify this behaviour on real hardware! ''' pass def test_EXG_undefined_to_X(self): ''' TODO: verify this behaviour on real hardware! ''' pass
7
4
10
0
8
5
1
0.55
1
0
0
0
6
0
6
89
67
5
49
7
42
27
31
7
24
1
4
0
6
1,379
6809/MC6809
6809_MC6809/MC6809/tests/test_cpu6809.py
MC6809.tests.test_cpu6809.Test6809_CC
class Test6809_CC(BaseCPUTestCase): """ condition code register tests """ def test_defaults(self): status_byte = self.cpu.get_cc_value() self.assertEqual(status_byte, 0) def test_from_to(self): for i in range(256): self.cpu.set_cc(i) status_byte = self.cpu.get_cc_value() self.assertEqual(status_byte, i) def test_AND(self): excpected_values = list(range(0, 128)) excpected_values += list(range(0, 128)) excpected_values += list(range(0, 4)) for i in range(260): self.cpu.accu_a.set(i) self.cpu.set_cc(0x0e) # Set affected flags: ....NZV. self.cpu_test_run(start=0x1000, end=None, mem=[ 0x84, 0x7f, # ANDA #$7F ]) r = self.cpu.accu_a.value excpected_value = excpected_values[i] # print i, r, excpected_value, self.cpu.get_info, self.cpu.get_cc_value() # test AND result self.assertEqual(r, excpected_value) # test all CC flags if r == 0: self.assertEqual(self.cpu.get_cc_value(), 4) else: self.assertEqual(self.cpu.get_cc_value(), 0)
class Test6809_CC(BaseCPUTestCase): ''' condition code register tests ''' def test_defaults(self): pass def test_from_to(self): pass def test_AND(self): pass
4
1
10
1
8
2
2
0.31
1
2
0
0
3
0
3
86
38
6
26
11
22
8
23
11
19
3
4
2
6
1,380
6809/MC6809
6809_MC6809/MC6809/tests/test_accumulators.py
MC6809.tests.test_accumulators.CC_AccumulatorTestCase
class CC_AccumulatorTestCase(BaseCPUTestCase): def test_A_01(self): self.cpu.accu_a.set(0xff) self.assertEqualHex(self.cpu.accu_a.value, 0xff) def test_A_02(self): self.cpu.accu_a.set(0xff + 1) self.assertEqualHex(self.cpu.accu_a.value, 0x00) def test_B_01(self): self.cpu.accu_b.set(0x5a) self.assertEqualHex(self.cpu.accu_b.value, 0x5a) self.assertEqual(self.cpu.V, 0) def test_B_02(self): self.cpu.accu_b.set(0xff + 10) self.assertEqualHex(self.cpu.accu_b.value, 0x09) def test_D_01(self): self.cpu.accu_a.set(0x12) self.cpu.accu_b.set(0xab) self.assertEqualHex(self.cpu.accu_d.value, 0x12ab) def test_D_02(self): self.cpu.accu_d.set(0xfd89) self.assertEqualHex(self.cpu.accu_a.value, 0xfd) self.assertEqualHex(self.cpu.accu_b.value, 0x89) def test_D_03(self): self.cpu.accu_d.set(0xffff + 1) self.assertEqualHex(self.cpu.accu_a.value, 0x00) self.assertEqualHex(self.cpu.accu_b.value, 0x00)
class CC_AccumulatorTestCase(BaseCPUTestCase): def test_A_01(self): pass def test_A_02(self): pass def test_B_01(self): pass def test_B_02(self): pass def test_D_01(self): pass def test_D_02(self): pass def test_D_03(self): pass
8
0
4
0
4
0
1
0
1
0
0
0
7
0
7
90
32
6
26
8
18
0
26
8
18
1
4
0
7
1,381
6809/MC6809
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/6809_MC6809/MC6809/components/mc6809_ops_logic.py
MC6809.components.mc6809_ops_logic.OpsLogicalMixin
class OpsLogicalMixin: # ---- Logical Operations ---- @opcode( # AND memory with accumulator 0x84, 0x94, 0xa4, 0xb4, # ANDA (immediate, direct, indexed, extended) 0xc4, 0xd4, 0xe4, 0xf4, # ANDB (immediate, direct, indexed, extended) ) def instruction_AND(self, opcode, m, register): """ Performs the logical AND operation between the contents of an accumulator and the contents of memory location M and the result is stored in the accumulator. source code forms: ANDA P; ANDB P CC bits "HNZVC": -aa0- """ a = register.value r = a & m register.set(r) self.clear_NZV() self.update_NZ_8(r) # log.debug("\tAND %s: %i & %i = %i", # register.name, a, m, r # ) @opcode( # Exclusive OR memory with accumulator 0x88, 0x98, 0xa8, 0xb8, # EORA (immediate, direct, indexed, extended) 0xc8, 0xd8, 0xe8, 0xf8, # EORB (immediate, direct, indexed, extended) ) def instruction_EOR(self, opcode, m, register): """ The contents of memory location M is exclusive ORed into an 8-bit register. source code forms: EORA P; EORB P CC bits "HNZVC": -aa0- """ a = register.value r = a ^ m register.set(r) self.clear_NZV() self.update_NZ_8(r) # log.debug("\tEOR %s: %i ^ %i = %i", # register.name, a, m, r # ) @opcode( # OR memory with accumulator 0x8a, 0x9a, 0xaa, 0xba, # ORA (immediate, direct, indexed, extended) 0xca, 0xda, 0xea, 0xfa, # ORB (immediate, direct, indexed, extended) ) def instruction_OR(self, opcode, m, register): """ Performs an inclusive OR operation between the contents of accumulator A or B and the contents of memory location M and the result is stored in accumulator A or B. source code forms: ORA P; ORB P CC bits "HNZVC": -aa0- """ a = register.value r = a | m register.set(r) self.clear_NZV() self.update_NZ_8(r) # log.debug("$%04x OR %s: %02x | %02x = %02x", # self.program_counter, register.name, a, m, r # ) # ---- CC manipulation ---- @opcode( # AND condition code register 0x1c, # ANDCC (immediate) ) def instruction_ANDCC(self, opcode, m, register): """ Performs a logical AND between the condition code register and the immediate byte specified in the instruction and places the result in the condition code register. source code forms: ANDCC #xx CC bits "HNZVC": ddddd """ assert register == self.cc_register old_cc = self.get_cc_value() new_cc = old_cc & m self.set_cc(new_cc) # log.debug("\tANDCC: $%x AND $%x = $%x | set CC to %s", # old_cc, m, new_cc, self.get_cc_info() # ) @opcode( # OR condition code register 0x1a, # ORCC (immediate) ) def instruction_ORCC(self, opcode, m, register): """ Performs an inclusive OR operation between the contents of the condition code registers and the immediate value, and the result is placed in the condition code register. This instruction may be used to set interrupt masks (disable interrupts) or any other bit(s). source code forms: ORCC #XX CC bits "HNZVC": ddddd """ assert register == self.cc_register old_cc = self.get_cc_value() new_cc = old_cc | m self.set_cc(new_cc) # log.debug("\tORCC: $%x OR $%x = $%x | set CC to %s", # old_cc, m, new_cc, self.get_cc_info() # ) # ---- Logical shift: LSL, LSR ---- def LSL(self, a): """ Shifts all bits of accumulator A or B or memory location M one place to the left. Bit zero is loaded with a zero. Bit seven of accumulator A or B or memory location M is shifted into the C (carry) bit. This is a duplicate assembly-language mnemonic for the single machine instruction ASL. source code forms: LSL Q; LSLA; LSLB CC bits "HNZVC": naaas """ r = a << 1 self.clear_NZVC() self.update_NZVC_8(a, a, r) return r @opcode(0x8, 0x68, 0x78) # LSL/ASL (direct, indexed, extended) def instruction_LSL_memory(self, opcode, ea, m): """ Logical shift left memory location / Arithmetic shift of memory left """ r = self.LSL(m) # log.debug("$%x LSL memory value $%x << 1 = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) # )) return ea, r & 0xff @opcode(0x48, 0x58) # LSLA/ASLA / LSLB/ASLB (inherent) def instruction_LSL_register(self, opcode, register): """ Logical shift left accumulator / Arithmetic shift of accumulator """ a = register.value r = self.LSL(a) # log.debug("$%x LSL %s value $%x << 1 = $%x" % ( # self.program_counter, # register.name, a, r # )) register.set(r) def LSR(self, a): """ Performs a logical shift right on the register. Shifts a zero into bit seven and bit zero into the C (carry) bit. source code forms: LSR Q; LSRA; LSRB CC bits "HNZVC": -0a-s """ r = a >> 1 self.clear_NZC() self.C = get_bit(a, bit=0) # same as: self.C |= (a & 1) self.set_Z8(r) return r @opcode(0x4, 0x64, 0x74) # LSR (direct, indexed, extended) def instruction_LSR_memory(self, opcode, ea, m): """ Logical shift right memory location """ r = self.LSR(m) # log.debug("$%x LSR memory value $%x >> 1 = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) # )) return ea, r & 0xff @opcode(0x44, 0x54) # LSRA / LSRB (inherent) def instruction_LSR_register(self, opcode, register): """ Logical shift right accumulator """ a = register.value r = self.LSR(a) # log.debug("$%x LSR %s value $%x >> 1 = $%x" % ( # self.program_counter, # register.name, a, r # )) register.set(r) def ASR(self, a): """ ASR (Arithmetic Shift Right) alias LSR (Logical Shift Right) Shifts all bits of the register one place to the right. Bit seven is held constant. Bit zero is shifted into the C (carry) bit. source code forms: ASR Q; ASRA; ASRB CC bits "HNZVC": uaa-s """ r = (a >> 1) | (a & 0x80) self.clear_NZC() self.C = get_bit(a, bit=0) # same as: self.C |= (a & 1) self.update_NZ_8(r) return r @opcode(0x7, 0x67, 0x77) # ASR (direct, indexed, extended) def instruction_ASR_memory(self, opcode, ea, m): """ Arithmetic shift memory right """ r = self.ASR(m) # log.debug("$%x ASR memory value $%x >> 1 | Carry = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) # )) return ea, r & 0xff @opcode(0x47, 0x57) # ASRA/ASRB (inherent) def instruction_ASR_register(self, opcode, register): """ Arithmetic shift accumulator right """ a = register.value r = self.ASR(a) # log.debug("$%x ASR %s value $%x >> 1 | Carry = $%x" % ( # self.program_counter, # register.name, a, r # )) register.set(r) # ---- Rotate: ROL, ROR ---- def ROL(self, a): """ Rotates all bits of the register one place left through the C (carry) bit. This is a 9-bit rotation. source code forms: ROL Q; ROLA; ROLB CC bits "HNZVC": -aaas """ r = (a << 1) | self.C self.clear_NZVC() self.update_NZVC_8(a, a, r) return r @opcode(0x9, 0x69, 0x79) # ROL (direct, indexed, extended) def instruction_ROL_memory(self, opcode, ea, m): """ Rotate memory left """ r = self.ROL(m) # log.debug("$%x ROL memory value $%x << 1 | Carry = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) # )) return ea, r & 0xff @opcode(0x49, 0x59) # ROLA / ROLB (inherent) def instruction_ROL_register(self, opcode, register): """ Rotate accumulator left """ a = register.value r = self.ROL(a) # log.debug("$%x ROL %s value $%x << 1 | Carry = $%x" % ( # self.program_counter, # register.name, a, r # )) register.set(r) def ROR(self, a): """ Rotates all bits of the register one place right through the C (carry) bit. This is a 9-bit rotation. moved the carry flag into bit 8 moved bit 7 into carry flag source code forms: ROR Q; RORA; RORB CC bits "HNZVC": -aa-s """ r = (a >> 1) | (self.C << 7) self.clear_NZ() self.update_NZ_8(r) self.C = get_bit(a, bit=0) # same as: self.C = (a & 1) return r @opcode(0x6, 0x66, 0x76) # ROR (direct, indexed, extended) def instruction_ROR_memory(self, opcode, ea, m): """ Rotate memory right """ r = self.ROR(m) # log.debug("$%x ROR memory value $%x >> 1 | Carry = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) # )) return ea, r & 0xff @opcode(0x46, 0x56) # RORA/RORB (inherent) def instruction_ROR_register(self, opcode, register): """ Rotate accumulator right """ a = register.value r = self.ROR(a) # log.debug("$%x ROR %s value $%x >> 1 | Carry = $%x" % ( # self.program_counter, # register.name, a, r # )) register.set(r)
class OpsLogicalMixin: @opcode( # AND memory with accumulator 0x84, 0x94, 0xa4, 0xb4, # ANDA (immediate, direct, indexed, extended) 0xc4, 0xd4, 0xe4, 0xf4, # ANDB (immediate, direct, indexed, extended) ) def instruction_AND(self, opcode, m, register): ''' Performs the logical AND operation between the contents of an accumulator and the contents of memory location M and the result is stored in the accumulator. source code forms: ANDA P; ANDB P CC bits "HNZVC": -aa0- ''' pass @opcode( # Exclusive OR memory with accumulator 0x88, 0x98, 0xa8, 0xb8, # EORA (immediate, direct, indexed, extended) 0xc8, 0xd8, 0xe8, 0xf8, # EORB (immediate, direct, indexed, extended) ) def instruction_EOR(self, opcode, m, register): ''' The contents of memory location M is exclusive ORed into an 8-bit register. source code forms: EORA P; EORB P CC bits "HNZVC": -aa0- ''' pass @opcode( # OR memory with accumulator 0x8a, 0x9a, 0xaa, 0xba, # ORA (immediate, direct, indexed, extended) 0xca, 0xda, 0xea, 0xfa, # ORB (immediate, direct, indexed, extended) ) def instruction_OR(self, opcode, m, register): ''' Performs an inclusive OR operation between the contents of accumulator A or B and the contents of memory location M and the result is stored in accumulator A or B. source code forms: ORA P; ORB P CC bits "HNZVC": -aa0- ''' pass @opcode( # AND condition code register 0x1c, # ANDCC (immediate) ) def instruction_ANDCC(self, opcode, m, register): ''' Performs a logical AND between the condition code register and the immediate byte specified in the instruction and places the result in the condition code register. source code forms: ANDCC #xx CC bits "HNZVC": ddddd ''' pass @opcode( # OR condition code register 0x1a, # ORCC (immediate) ) def instruction_ORCC(self, opcode, m, register): ''' Performs an inclusive OR operation between the contents of the condition code registers and the immediate value, and the result is placed in the condition code register. This instruction may be used to set interrupt masks (disable interrupts) or any other bit(s). source code forms: ORCC #XX CC bits "HNZVC": ddddd ''' pass def LSL(self, a): ''' Shifts all bits of accumulator A or B or memory location M one place to the left. Bit zero is loaded with a zero. Bit seven of accumulator A or B or memory location M is shifted into the C (carry) bit. This is a duplicate assembly-language mnemonic for the single machine instruction ASL. source code forms: LSL Q; LSLA; LSLB CC bits "HNZVC": naaas ''' pass @opcode(0x8, 0x68, 0x78) def instruction_LSL_memory(self, opcode, ea, m): ''' Logical shift left memory location / Arithmetic shift of memory left ''' pass @opcode(0x48, 0x58) def instruction_LSL_register(self, opcode, register): ''' Logical shift left accumulator / Arithmetic shift of accumulator ''' pass def LSR(self, a): ''' Performs a logical shift right on the register. Shifts a zero into bit seven and bit zero into the C (carry) bit. source code forms: LSR Q; LSRA; LSRB CC bits "HNZVC": -0a-s ''' pass @opcode(0x4, 0x64, 0x74) def instruction_LSR_memory(self, opcode, ea, m): ''' Logical shift right memory location ''' pass @opcode(0x44, 0x54) def instruction_LSR_register(self, opcode, register): ''' Logical shift right accumulator ''' pass def ASR(self, a): ''' ASR (Arithmetic Shift Right) alias LSR (Logical Shift Right) Shifts all bits of the register one place to the right. Bit seven is held constant. Bit zero is shifted into the C (carry) bit. source code forms: ASR Q; ASRA; ASRB CC bits "HNZVC": uaa-s ''' pass @opcode(0x7, 0x67, 0x77) def instruction_ASR_memory(self, opcode, ea, m): ''' Arithmetic shift memory right ''' pass @opcode(0x47, 0x57) def instruction_ASR_register(self, opcode, register): ''' Arithmetic shift accumulator right ''' pass def ROL(self, a): ''' Rotates all bits of the register one place left through the C (carry) bit. This is a 9-bit rotation. source code forms: ROL Q; ROLA; ROLB CC bits "HNZVC": -aaas ''' pass @opcode(0x9, 0x69, 0x79) def instruction_ROL_memory(self, opcode, ea, m): ''' Rotate memory left ''' pass @opcode(0x49, 0x59) def instruction_ROL_register(self, opcode, register): ''' Rotate accumulator left ''' pass def ROR(self, a): ''' Rotates all bits of the register one place right through the C (carry) bit. This is a 9-bit rotation. moved the carry flag into bit 8 moved bit 7 into carry flag source code forms: ROR Q; RORA; RORB CC bits "HNZVC": -aa-s ''' pass @opcode(0x6, 0x66, 0x76) def instruction_ROR_memory(self, opcode, ea, m): ''' Rotate memory right ''' pass @opcode(0x46, 0x56) def instruction_ROR_register(self, opcode, register): ''' Rotate accumulator right ''' pass
36
20
12
1
5
7
1
1.46
0
0
0
1
20
1
20
20
317
48
120
80
71
175
92
52
71
1
0
0
20
1,382
6809/MC6809
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/6809_MC6809/MC6809/components/mc6809_ops_load_store.py
MC6809.components.mc6809_ops_load_store.OpsLoadStoreMixin
class OpsLoadStoreMixin: # ---- Store / Load ---- @opcode( # Load register from memory 0xcc, 0xdc, 0xec, 0xfc, # LDD (immediate, direct, indexed, extended) # LDS (immediate, direct, indexed, extended) 0x10ce, 0x10de, 0x10ee, 0x10fe, 0xce, 0xde, 0xee, 0xfe, # LDU (immediate, direct, indexed, extended) 0x8e, 0x9e, 0xae, 0xbe, # LDX (immediate, direct, indexed, extended) # LDY (immediate, direct, indexed, extended) 0x108e, 0x109e, 0x10ae, 0x10be, ) def instruction_LD16(self, opcode, m, register): """ Load the contents of the memory location M:M+1 into the designated 16-bit register. source code forms: LDD P; LDX P; LDY P; LDS P; LDU P CC bits "HNZVC": -aa0- """ # log.debug("$%x LD16 set %s to $%x \t| %s" % ( # self.program_counter, # register.name, m, # self.cfg.mem_info.get_shortest(m) # )) register.set(m) self.clear_NZV() self.update_NZ_16(m) @opcode( # Load accumulator from memory 0x86, 0x96, 0xa6, 0xb6, # LDA (immediate, direct, indexed, extended) 0xc6, 0xd6, 0xe6, 0xf6, # LDB (immediate, direct, indexed, extended) ) def instruction_LD8(self, opcode, m, register): """ Loads the contents of memory location M into the designated register. source code forms: LDA P; LDB P CC bits "HNZVC": -aa0- """ # log.debug("$%x LD8 %s = $%x" % ( # self.program_counter, # register.name, m, # )) register.set(m) self.clear_NZV() self.update_NZ_8(m) @opcode( # Store register to memory 0xdd, 0xed, 0xfd, # STD (direct, indexed, extended) 0x10df, 0x10ef, 0x10ff, # STS (direct, indexed, extended) 0xdf, 0xef, 0xff, # STU (direct, indexed, extended) 0x9f, 0xaf, 0xbf, # STX (direct, indexed, extended) 0x109f, 0x10af, 0x10bf, # STY (direct, indexed, extended) ) def instruction_ST16(self, opcode, ea, register): """ Writes the contents of a 16-bit register into two consecutive memory locations. source code forms: STD P; STX P; STY P; STS P; STU P CC bits "HNZVC": -aa0- """ value = register.value # log.debug("$%x ST16 store value $%x from %s at $%x \t| %s" % ( # self.program_counter, # value, register.name, ea, # self.cfg.mem_info.get_shortest(ea) # )) self.clear_NZV() self.update_NZ_16(value) return ea, value # write word to Memory @opcode( # Store accumulator to memory 0x97, 0xa7, 0xb7, # STA (direct, indexed, extended) 0xd7, 0xe7, 0xf7, # STB (direct, indexed, extended) ) def instruction_ST8(self, opcode, ea, register): """ Writes the contents of an 8-bit register into a memory location. source code forms: STA P; STB P CC bits "HNZVC": -aa0- """ value = register.value # log.debug("$%x ST8 store value $%x from %s at $%x \t| %s" % ( # self.program_counter, # value, register.name, ea, # self.cfg.mem_info.get_shortest(ea) # )) self.clear_NZV() self.update_NZ_8(value) return ea, value
class OpsLoadStoreMixin: @opcode( # Load register from memory 0xcc, 0xdc, 0xec, 0xfc, # LDD (immediate, direct, indexed, extended) # LDS (immediate, direct, indexed, extended) 0x10ce, 0x10de, 0x10ee, 0x10fe, 0xce, 0xde, 0xee, 0xfe, # LDU (immediate, direct, indexed, extended) 0x8e, 0x9e, 0xae, 0xbe, # LDX (immediate, direct, indexed, extended) # LDY (immediate, direct, indexed, extended) 0x108e, 0x109e, 0x10ae, 0x10be, ) def instruction_LD16(self, opcode, m, register): ''' Load the contents of the memory location M:M+1 into the designated 16-bit register. source code forms: LDD P; LDX P; LDY P; LDS P; LDU P CC bits "HNZVC": -aa0- ''' pass @opcode( # Load accumulator from memory 0x86, 0x96, 0xa6, 0xb6, # LDA (immediate, direct, indexed, extended) 0xc6, 0xd6, 0xe6, 0xf6, # LDB (immediate, direct, indexed, extended) ) def instruction_LD8(self, opcode, m, register): ''' Loads the contents of memory location M into the designated register. source code forms: LDA P; LDB P CC bits "HNZVC": -aa0- ''' pass @opcode( # Store register to memory 0xdd, 0xed, 0xfd, # STD (direct, indexed, extended) 0x10df, 0x10ef, 0x10ff, # STS (direct, indexed, extended) 0xdf, 0xef, 0xff, # STU (direct, indexed, extended) 0x9f, 0xaf, 0xbf, # STX (direct, indexed, extended) 0x109f, 0x10af, 0x10bf, # STY (direct, indexed, extended) ) def instruction_ST16(self, opcode, ea, register): ''' Writes the contents of a 16-bit register into two consecutive memory locations. source code forms: STD P; STX P; STY P; STS P; STU P CC bits "HNZVC": -aa0- ''' pass @opcode( # Store accumulator to memory 0x97, 0xa7, 0xb7, # STA (direct, indexed, extended) 0xd7, 0xe7, 0xf7, # STB (direct, indexed, extended) ) def instruction_ST8(self, opcode, ea, register): ''' Writes the contents of an 8-bit register into a memory location. source code forms: STA P; STB P CC bits "HNZVC": -aa0- ''' pass
9
4
17
2
5
11
1
1.51
0
0
0
1
4
0
4
4
96
13
41
29
14
62
19
7
14
1
0
0
4
1,383
6809/MC6809
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/6809_MC6809/MC6809/components/mc6809_ops_branches.py
MC6809.components.mc6809_ops_branches.OpsBranchesMixin
class OpsBranchesMixin: # ---- Programm Flow Instructions ---- @opcode( # Jump 0xe, 0x6e, 0x7e, # JMP (direct, indexed, extended) ) def instruction_JMP(self, opcode, ea): """ Program control is transferred to the effective address. source code forms: JMP EA CC bits "HNZVC": ----- """ # log.info("%x|\tJMP to $%x \t| %s" % ( # self.last_op_address, # ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) @opcode( # Return from subroutine 0x39, # RTS (inherent) ) def instruction_RTS(self, opcode): """ Program control is returned from the subroutine to the calling program. The return address is pulled from the stack. source code forms: RTS CC bits "HNZVC": ----- """ ea = self.pull_word(self.system_stack_pointer) # log.info("%x|\tRTS to $%x \t| %s" % ( # self.last_op_address, # ea, # self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) @opcode( # Branch to subroutine: 0x8d, # BSR (relative) 0x17, # LBSR (relative) # Jump to subroutine: 0x9d, 0xad, 0xbd, # JSR (direct, indexed, extended) ) def instruction_BSR_JSR(self, opcode, ea): """ Program control is transferred to the effective address after storing the return address on the hardware stack. A return from subroutine (RTS) instruction is used to reverse this process and must be the last instruction executed in a subroutine. source code forms: BSR dd; LBSR DDDD; JSR EA CC bits "HNZVC": ----- """ # log.info("%x|\tJSR/BSR to $%x \t| %s" % ( # self.last_op_address, # ea, self.cfg.mem_info.get_shortest(ea) # )) self.push_word(self.system_stack_pointer, self.program_counter.value) self.program_counter.set(ea) # ---- Branch Instructions ---- @opcode( # Branch if equal 0x27, # BEQ (relative) 0x1027, # LBEQ (relative) ) def instruction_BEQ(self, opcode, ea): """ Tests the state of the Z (zero) bit and causes a branch if it is set. When used after a subtract or compare operation, this instruction will branch if the compared values, signed or unsigned, were exactly the same. source code forms: BEQ dd; LBEQ DDDD CC bits "HNZVC": ----- """ if self.Z == 1: # log.info("$%x BEQ branch to $%x, because Z==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BEQ: don't branch to $%x, because Z==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch if greater than or equal (signed) 0x2c, # BGE (relative) 0x102c, # LBGE (relative) ) def instruction_BGE(self, opcode, ea): """ Causes a branch if the N (negative) bit and the V (overflow) bit are either both set or both clear. That is, branch if the sign of a valid twos complement result is, or would be, positive. When used after a subtract or compare operation on twos complement values, this instruction will branch if the register was greater than or equal to the memory register. source code forms: BGE dd; LBGE DDDD CC bits "HNZVC": ----- """ # Note these variantes are the same: # self.N == self.V # (self.N ^ self.V) == 0 # not operator.xor(self.N, self.V) if self.N == self.V: # log.info("$%x BGE branch to $%x, because N XOR V == 0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BGE: don't branch to $%x, because N XOR V != 0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch if greater (signed) 0x2e, # BGT (relative) 0x102e, # LBGT (relative) ) def instruction_BGT(self, opcode, ea): """ Causes a branch if the N (negative) bit and V (overflow) bit are either both set or both clear and the Z (zero) bit is clear. In other words, branch if the sign of a valid twos complement result is, or would be, positive and not zero. When used after a subtract or compare operation on twos complement values, this instruction will branch if the register was greater than the memory register. source code forms: BGT dd; LBGT DDDD CC bits "HNZVC": ----- """ # Note these variantes are the same: # not ((self.N ^ self.V) == 1 or self.Z == 1) # not ((self.N ^ self.V) | self.Z) # self.N == self.V and self.Z == 0 # ;) if not self.Z and self.N == self.V: # log.info("$%x BGT branch to $%x, because (N==V and Z==0) \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BGT: don't branch to $%x, because (N==V and Z==0) is False \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch if higher (unsigned) 0x22, # BHI (relative) 0x1022, # LBHI (relative) ) def instruction_BHI(self, opcode, ea): """ Causes a branch if the previous operation caused neither a carry nor a zero result. When used after a subtract or compare operation on unsigned binary values, this instruction will branch if the register was higher than the memory register. Generally not useful after INC/DEC, LD/TST, and TST/CLR/COM instructions. source code forms: BHI dd; LBHI DDDD CC bits "HNZVC": ----- """ if self.C == 0 and self.Z == 0: # log.info("$%x BHI branch to $%x, because C==0 and Z==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BHI: don't branch to $%x, because C and Z not 0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch if less than or equal (signed) 0x2f, # BLE (relative) 0x102f, # LBLE (relative) ) def instruction_BLE(self, opcode, ea): """ Causes a branch if the exclusive OR of the N (negative) and V (overflow) bits is 1 or if the Z (zero) bit is set. That is, branch if the sign of a valid twos complement result is, or would be, negative. When used after a subtract or compare operation on twos complement values, this instruction will branch if the register was less than or equal to the memory register. source code forms: BLE dd; LBLE DDDD CC bits "HNZVC": ----- """ if (self.N ^ self.V) == 1 or self.Z == 1: # log.info("$%x BLE branch to $%x, because N^V==1 or Z==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BLE: don't branch to $%x, because N^V!=1 and Z!=1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch if lower or same (unsigned) 0x23, # BLS (relative) 0x1023, # LBLS (relative) ) def instruction_BLS(self, opcode, ea): """ Causes a branch if the previous operation caused either a carry or a zero result. When used after a subtract or compare operation on unsigned binary values, this instruction will branch if the register was lower than or the same as the memory register. Generally not useful after INC/DEC, LD/ST, and TST/CLR/COM instructions. source code forms: BLS dd; LBLS DDDD CC bits "HNZVC": ----- """ # if (self.C|self.Z) == 0: if self.C == 1 or self.Z == 1: # log.info("$%x BLS branch to $%x, because C|Z==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BLS: don't branch to $%x, because C|Z!=1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch if less than (signed) 0x2d, # BLT (relative) 0x102d, # LBLT (relative) ) def instruction_BLT(self, opcode, ea): """ Causes a branch if either, but not both, of the N (negative) or V (overflow) bits is set. That is, branch if the sign of a valid twos complement result is, or would be, negative. When used after a subtract or compare operation on twos complement binary values, this instruction will branch if the register was less than the memory register. source code forms: BLT dd; LBLT DDDD CC bits "HNZVC": ----- """ if (self.N ^ self.V) == 1: # N xor V # log.info("$%x BLT branch to $%x, because N XOR V == 1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BLT: don't branch to $%x, because N XOR V != 1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch if minus 0x2b, # BMI (relative) 0x102b, # LBMI (relative) ) def instruction_BMI(self, opcode, ea): """ Tests the state of the N (negative) bit and causes a branch if set. That is, branch if the sign of the twos complement result is negative. When used after an operation on signed binary values, this instruction will branch if the result is minus. It is generally preferred to use the LBLT instruction after signed operations. source code forms: BMI dd; LBMI DDDD CC bits "HNZVC": ----- """ if self.N == 1: # log.info("$%x BMI branch to $%x, because N==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BMI: don't branch to $%x, because N==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch if not equal 0x26, # BNE (relative) 0x1026, # LBNE (relative) ) def instruction_BNE(self, opcode, ea): """ Tests the state of the Z (zero) bit and causes a branch if it is clear. When used after a subtract or compare operation on any binary values, this instruction will branch if the register is, or would be, not equal to the memory register. source code forms: BNE dd; LBNE DDDD CC bits "HNZVC": ----- """ if self.Z == 0: # log.info("$%x BNE branch to $%x, because Z==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BNE: don't branch to $%x, because Z==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch if plus 0x2a, # BPL (relative) 0x102a, # LBPL (relative) ) def instruction_BPL(self, opcode, ea): """ Tests the state of the N (negative) bit and causes a branch if it is clear. That is, branch if the sign of the twos complement result is positive. When used after an operation on signed binary values, this instruction will branch if the result (possibly invalid) is positive. It is generally preferred to use the BGE instruction after signed operations. source code forms: BPL dd; LBPL DDDD CC bits "HNZVC": ----- """ if self.N == 0: # log.info("$%x BPL branch to $%x, because N==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BPL: don't branch to $%x, because N==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch always 0x20, # BRA (relative) 0x16, # LBRA (relative) ) def instruction_BRA(self, opcode, ea): """ Causes an unconditional branch. source code forms: BRA dd; LBRA DDDD CC bits "HNZVC": ----- """ # log.info("$%x BRA branch to $%x \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) @opcode( # Branch never 0x21, # BRN (relative) 0x1021, # LBRN (relative) ) def instruction_BRN(self, opcode, ea): """ Does not cause a branch. This instruction is essentially a no operation, but has a bit pattern logically related to branch always. source code forms: BRN dd; LBRN DDDD CC bits "HNZVC": ----- """ pass @opcode( # Branch if valid twos complement result 0x28, # BVC (relative) 0x1028, # LBVC (relative) ) def instruction_BVC(self, opcode, ea): """ Tests the state of the V (overflow) bit and causes a branch if it is clear. That is, branch if the twos complement result was valid. When used after an operation on twos complement binary values, this instruction will branch if there was no overflow. source code forms: BVC dd; LBVC DDDD CC bits "HNZVC": ----- """ if self.V == 0: # log.info("$%x BVC branch to $%x, because V==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BVC: don't branch to $%x, because V==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch if invalid twos complement result 0x29, # BVS (relative) 0x1029, # LBVS (relative) ) def instruction_BVS(self, opcode, ea): """ Tests the state of the V (overflow) bit and causes a branch if it is set. That is, branch if the twos complement result was invalid. When used after an operation on twos complement binary values, this instruction will branch if there was an overflow. source code forms: BVS dd; LBVS DDDD CC bits "HNZVC": ----- """ if self.V == 1: # log.info("$%x BVS branch to $%x, because V==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BVS: don't branch to $%x, because V==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch if lower (unsigned) 0x25, # BLO/BCS (relative) 0x1025, # LBLO/LBCS (relative) ) def instruction_BLO(self, opcode, ea): """ CC bits "HNZVC": ----- case 0x5: cond = REG_CC & CC_C; break; // BCS, BLO, LBCS, LBLO """ if self.C == 1: # log.info("$%x BLO/BCS/LBLO/LBCS branch to $%x, because C==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea) # else: # log.debug("$%x BLO/BCS/LBLO/LBCS: don't branch to $%x, because C==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) @opcode( # Branch if lower (unsigned) 0x24, # BHS/BCC (relative) 0x1024, # LBHS/LBCC (relative) ) def instruction_BHS(self, opcode, ea): """ CC bits "HNZVC": ----- case 0x4: cond = !(REG_CC & CC_C); break; // BCC, BHS, LBCC, LBHS """ if self.C == 0: # log.info("$%x BHS/BCC/LBHS/LBCC branch to $%x, because C==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
class OpsBranchesMixin: @opcode( # Jump 0xe, 0x6e, 0x7e, # JMP (direct, indexed, extended) ) def instruction_JMP(self, opcode, ea): ''' Program control is transferred to the effective address. source code forms: JMP EA CC bits "HNZVC": ----- ''' pass @opcode( # Return from subroutine 0x39, # RTS (inherent) ) def instruction_RTS(self, opcode): ''' Program control is returned from the subroutine to the calling program. The return address is pulled from the stack. source code forms: RTS CC bits "HNZVC": ----- ''' pass @opcode( # Branch to subroutine: 0x8d, # BSR (relative) 0x17, # LBSR (relative) # Jump to subroutine: 0x9d, 0xad, 0xbd, # JSR (direct, indexed, extended) ) def instruction_BSR_JSR(self, opcode, ea): ''' Program control is transferred to the effective address after storing the return address on the hardware stack. A return from subroutine (RTS) instruction is used to reverse this process and must be the last instruction executed in a subroutine. source code forms: BSR dd; LBSR DDDD; JSR EA CC bits "HNZVC": ----- ''' pass @opcode( # Branch if equal 0x27, # BEQ (relative) 0x1027, # LBEQ (relative) ) def instruction_BEQ(self, opcode, ea): ''' Tests the state of the Z (zero) bit and causes a branch if it is set. When used after a subtract or compare operation, this instruction will branch if the compared values, signed or unsigned, were exactly the same. source code forms: BEQ dd; LBEQ DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch if greater than or equal (signed) 0x2c, # BGE (relative) 0x102c, # LBGE (relative) ) def instruction_BGE(self, opcode, ea): ''' Causes a branch if the N (negative) bit and the V (overflow) bit are either both set or both clear. That is, branch if the sign of a valid twos complement result is, or would be, positive. When used after a subtract or compare operation on twos complement values, this instruction will branch if the register was greater than or equal to the memory register. source code forms: BGE dd; LBGE DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch if greater (signed) 0x2e, # BGT (relative) 0x102e, # LBGT (relative) ) def instruction_BGT(self, opcode, ea): ''' Causes a branch if the N (negative) bit and V (overflow) bit are either both set or both clear and the Z (zero) bit is clear. In other words, branch if the sign of a valid twos complement result is, or would be, positive and not zero. When used after a subtract or compare operation on twos complement values, this instruction will branch if the register was greater than the memory register. source code forms: BGT dd; LBGT DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch if higher (unsigned) 0x22, # BHI (relative) 0x1022, # LBHI (relative) ) def instruction_BHI(self, opcode, ea): ''' Causes a branch if the previous operation caused neither a carry nor a zero result. When used after a subtract or compare operation on unsigned binary values, this instruction will branch if the register was higher than the memory register. Generally not useful after INC/DEC, LD/TST, and TST/CLR/COM instructions. source code forms: BHI dd; LBHI DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch if less than or equal (signed) 0x2f, # BLE (relative) 0x102f, # LBLE (relative) ) def instruction_BLE(self, opcode, ea): ''' Causes a branch if the exclusive OR of the N (negative) and V (overflow) bits is 1 or if the Z (zero) bit is set. That is, branch if the sign of a valid twos complement result is, or would be, negative. When used after a subtract or compare operation on twos complement values, this instruction will branch if the register was less than or equal to the memory register. source code forms: BLE dd; LBLE DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch if lower or same (unsigned) 0x23, # BLS (relative) 0x1023, # LBLS (relative) ) def instruction_BLS(self, opcode, ea): ''' Causes a branch if the previous operation caused either a carry or a zero result. When used after a subtract or compare operation on unsigned binary values, this instruction will branch if the register was lower than or the same as the memory register. Generally not useful after INC/DEC, LD/ST, and TST/CLR/COM instructions. source code forms: BLS dd; LBLS DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch if less than (signed) 0x2d, # BLT (relative) 0x102d, # LBLT (relative) ) def instruction_BLT(self, opcode, ea): ''' Causes a branch if either, but not both, of the N (negative) or V (overflow) bits is set. That is, branch if the sign of a valid twos complement result is, or would be, negative. When used after a subtract or compare operation on twos complement binary values, this instruction will branch if the register was less than the memory register. source code forms: BLT dd; LBLT DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch if minus 0x2b, # BMI (relative) 0x102b, # LBMI (relative) ) def instruction_BMI(self, opcode, ea): ''' Tests the state of the N (negative) bit and causes a branch if set. That is, branch if the sign of the twos complement result is negative. When used after an operation on signed binary values, this instruction will branch if the result is minus. It is generally preferred to use the LBLT instruction after signed operations. source code forms: BMI dd; LBMI DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch if not equal 0x26, # BNE (relative) 0x1026, # LBNE (relative) ) def instruction_BNE(self, opcode, ea): ''' Tests the state of the Z (zero) bit and causes a branch if it is clear. When used after a subtract or compare operation on any binary values, this instruction will branch if the register is, or would be, not equal to the memory register. source code forms: BNE dd; LBNE DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch if plus 0x2a, # BPL (relative) 0x102a, # LBPL (relative) ) def instruction_BPL(self, opcode, ea): ''' Tests the state of the N (negative) bit and causes a branch if it is clear. That is, branch if the sign of the twos complement result is positive. When used after an operation on signed binary values, this instruction will branch if the result (possibly invalid) is positive. It is generally preferred to use the BGE instruction after signed operations. source code forms: BPL dd; LBPL DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch always 0x20, # BRA (relative) 0x16, # LBRA (relative) ) def instruction_BRA(self, opcode, ea): ''' Causes an unconditional branch. source code forms: BRA dd; LBRA DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch never 0x21, # BRN (relative) 0x1021, # LBRN (relative) ) def instruction_BRN(self, opcode, ea): ''' Does not cause a branch. This instruction is essentially a no operation, but has a bit pattern logically related to branch always. source code forms: BRN dd; LBRN DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch if valid twos complement result 0x28, # BVC (relative) 0x1028, # LBVC (relative) ) def instruction_BVC(self, opcode, ea): ''' Tests the state of the V (overflow) bit and causes a branch if it is clear. That is, branch if the twos complement result was valid. When used after an operation on twos complement binary values, this instruction will branch if there was no overflow. source code forms: BVC dd; LBVC DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch if invalid twos complement result 0x29, # BVS (relative) 0x1029, # LBVS (relative) ) def instruction_BVS(self, opcode, ea): ''' Tests the state of the V (overflow) bit and causes a branch if it is set. That is, branch if the twos complement result was invalid. When used after an operation on twos complement binary values, this instruction will branch if there was an overflow. source code forms: BVS dd; LBVS DDDD CC bits "HNZVC": ----- ''' pass @opcode( # Branch if lower (unsigned) 0x25, # BLO/BCS (relative) 0x1025, # LBLO/LBCS (relative) ) def instruction_BLO(self, opcode, ea): ''' CC bits "HNZVC": ----- case 0x5: cond = REG_CC & CC_C; break; // BCS, BLO, LBCS, LBLO ''' pass @opcode( # Branch if lower (unsigned) 0x24, # BHS/BCC (relative) 0x1024, # LBHS/LBCC (relative) ) def instruction_BHS(self, opcode, ea): ''' CC bits "HNZVC": ----- case 0x4: cond = !(REG_CC & CC_C); break; // BCC, BHS, LBCC, LBHS ''' pass
39
19
16
2
3
11
2
2.52
0
0
0
1
19
0
19
19
461
60
130
96
35
327
55
21
35
2
0
1
33
1,384
6809/MC6809
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/6809_MC6809/MC6809/components/mc6809_base.py
MC6809.components.mc6809_base.CPUBase
class CPUBase: SWI3_VECTOR = 0xfff2 SWI2_VECTOR = 0xfff4 FIRQ_VECTOR = 0xfff6 IRQ_VECTOR = 0xfff8 SWI_VECTOR = 0xfffa NMI_VECTOR = 0xfffc RESET_VECTOR = 0xfffe STARTUP_BURST_COUNT = 100 min_burst_count = 10 # minimum outer op count per burst max_burst_count = 10000 # maximum outer op count per burst def __init__(self, memory, cfg): self.memory = memory self.memory.cpu = self # FIXME self.cfg = cfg self.running = True self.cycles = 0 self.last_op_address = 0 # Store the current run opcode memory address self.outer_burst_op_count = self.STARTUP_BURST_COUNT # start_http_control_server(self, cfg) # TODO: Move into seperate Class self.index_x = ValueStorage16Bit(REG_X, 0) # X - 16 bit index register self.index_y = ValueStorage16Bit(REG_Y, 0) # Y - 16 bit index register self.user_stack_pointer = ValueStorage16Bit( REG_U, 0) # U - 16 bit user-stack pointer self.user_stack_pointer.counter = 0 # S - 16 bit system-stack pointer: # Position will be set by ROM code after detection of total installed RAM self.system_stack_pointer = ValueStorage16Bit(REG_S, 0) # PC - 16 bit program counter register self.program_counter = ValueStorage16Bit(REG_PC, 0) self.accu_a = ValueStorage8Bit(REG_A, 0) # A - 8 bit accumulator self.accu_b = ValueStorage8Bit(REG_B, 0) # B - 8 bit accumulator # D - 16 bit concatenated reg. (A + B) self.accu_d = ConcatenatedAccumulator(REG_D, self.accu_a, self.accu_b) # DP - 8 bit direct page register self.direct_page = ValueStorage8Bit(REG_DP, 0) super().__init__() self.register_str2object = { REG_X: self.index_x, REG_Y: self.index_y, REG_U: self.user_stack_pointer, REG_S: self.system_stack_pointer, REG_PC: self.program_counter, REG_A: self.accu_a, REG_B: self.accu_b, REG_D: self.accu_d, REG_DP: self.direct_page, REG_CC: self.cc_register, undefined_reg.name: undefined_reg, # for TFR, EXG } # log.debug("Add opcode functions:") self.opcode_dict = OpCollection(self).get_opcode_dict() # log.debug("illegal ops: %s" % ",".join(["$%x" % c for c in ILLEGAL_OPS])) # add illegal instruction # for opcode in ILLEGAL_OPS: # self.opcode_dict[opcode] = IllegalInstruction(self, opcode) def get_state(self): """ used in unittests """ return { REG_X: self.index_x.value, REG_Y: self.index_y.value, REG_U: self.user_stack_pointer.value, REG_S: self.system_stack_pointer.value, REG_PC: self.program_counter.value, REG_A: self.accu_a.value, REG_B: self.accu_b.value, REG_DP: self.direct_page.value, REG_CC: self.get_cc_value(), "cycles": self.cycles, "RAM": tuple(self.memory._mem) # copy of array.array() values, } def set_state(self, state): """ used in unittests """ self.index_x.set(state[REG_X]) self.index_y.set(state[REG_Y]) self.user_stack_pointer.set(state[REG_U]) self.system_stack_pointer.set(state[REG_S]) self.program_counter.set(state[REG_PC]) self.accu_a.set(state[REG_A]) self.accu_b.set(state[REG_B]) self.direct_page.set(state[REG_DP]) self.set_cc(state[REG_CC]) self.cycles = state["cycles"] self.memory.load(address=0x0000, data=state["RAM"]) #### def reset(self): log.info("%04x| CPU reset:", self.program_counter.value) self.last_op_address = 0 if self.cfg.__class__.__name__ == "SBC09Cfg": # first op is: # E400: 1AFF reset orcc #$FF ;Disable interrupts. # log.debug("\tset CC register to 0xff") # self.set_cc(0xff) log.info("\tset CC register to 0x00") self.set_cc(0x00) else: # log.info("\tset cc.F=1: FIRQ interrupt masked") # self.F = 1 # # log.info("\tset cc.I=1: IRQ interrupt masked") # self.I = 1 log.info("\tset E - 0x80 - bit 7 - Entire register state stacked") self.E = 1 # log.debug("\tset PC to $%x" % self.cfg.RESET_VECTOR) # self.program_counter = self.cfg.RESET_VECTOR log.info("\tread reset vector from $%04x", self.RESET_VECTOR) ea = self.memory.read_word(self.RESET_VECTOR) log.info(f"\tset PC to ${ea:04x}") if ea == 0x0000: log.critical( "Reset vector is $%04x ??? ROM loading in the right place?!?", ea) self.program_counter.set(ea) #### def get_and_call_next_op(self): op_address, opcode = self.read_pc_byte() # try: self.call_instruction_func(op_address, opcode) # except Exception as err: # try: # msg = "%s - op address: $%04x - opcode: $%02x" % (err, op_address, opcode) # except TypeError: # e.g: op_address or opcode is None # msg = "%s - op address: %r - opcode: %r" % (err, op_address, opcode) # exception = err.__class__ # Use origin Exception class, e.g.: KeyError # raise exception(msg) def quit(self): log.critical("CPU quit() called.") self.running = False def call_instruction_func(self, op_address, opcode): self.last_op_address = op_address try: cycles, instr_func = self.opcode_dict[opcode] except KeyError: msg = f"${op_address:x} *** UNKNOWN OP ${opcode:x}" log.error(msg) sys.exit(msg) instr_func(opcode) self.cycles += cycles #### # TODO: Move to __init__ quickest_sync_callback_cycles = None sync_callbacks_cyles = {} sync_callbacks = [] def add_sync_callback(self, callback_cycles, callback): """ Add a CPU cycle triggered callback """ self.sync_callbacks_cyles[callback] = 0 self.sync_callbacks.append([callback_cycles, callback]) if self.quickest_sync_callback_cycles is None or \ self.quickest_sync_callback_cycles > callback_cycles: self.quickest_sync_callback_cycles = callback_cycles def call_sync_callbacks(self): """ Call every sync callback with CPU cycles trigger """ current_cycles = self.cycles for callback_cycles, callback in self.sync_callbacks: # get the CPU cycles count of the last call last_call_cycles = self.sync_callbacks_cyles[callback] if current_cycles - last_call_cycles > callback_cycles: # this callback should be called # Save the current cycles, to trigger the next call self.sync_callbacks_cyles[callback] = self.cycles # Call the callback function callback(current_cycles - last_call_cycles) # TODO: Move to __init__ inner_burst_op_count = 100 # How many ops calls, before next sync call def burst_run(self): """ Run CPU as fast as Python can... """ # https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots... get_and_call_next_op = self.get_and_call_next_op for __ in range(self.outer_burst_op_count): for __ in range(self.inner_burst_op_count): get_and_call_next_op() self.call_sync_callbacks() def run(self, max_run_time=0.1, target_cycles_per_sec=None): now = time.time start_time = now() if target_cycles_per_sec is not None: # Run CPU not faster than given speedlimit self.delayed_burst_run(target_cycles_per_sec) else: # Run CPU as fast as Python can... self.delay = 0 self.burst_run() # Calculate the outer_burst_count new, to hit max_run_time self.outer_burst_op_count = calc_new_count( min_value=self.min_burst_count, value=self.outer_burst_op_count, max_value=self.max_burst_count, trigger=now() - start_time - self.delay, target=max_run_time ) def test_run(self, start, end, max_ops=1000000): # log.warning("CPU test_run(): from $%x to $%x" % (start, end)) self.program_counter.set(start) # log.debug("-"*79) # https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots... get_and_call_next_op = self.get_and_call_next_op program_counter = self.program_counter for __ in range(max_ops): if program_counter.value == end: return get_and_call_next_op() log.critical("Max ops %i arrived!", max_ops) raise RuntimeError(f"Max ops {max_ops:d} arrived!") def test_run2(self, start, count): # log.warning("CPU test_run2(): from $%x count: %i" % (start, count)) self.program_counter.set(start) # log.debug("-"*79) _old_burst_count = self.outer_burst_op_count self.outer_burst_op_count = count _old_sync_count = self.inner_burst_op_count self.inner_burst_op_count = 1 self.burst_run() self.outer_burst_op_count = _old_burst_count self.inner_burst_op_count = _old_sync_count #### @property def get_info(self): return "cc={:02x} a={:02x} b={:02x} dp={:02x} x={:04x} y={:04x} u={:04x} s={:04x}".format( self.get_cc_value(), self.accu_a.value, self.accu_b.value, self.direct_page.value, self.index_x.value, self.index_y.value, self.user_stack_pointer.value, self.system_stack_pointer.value ) #### def read_pc_byte(self): op_addr = self.program_counter.value m = self.memory.read_byte(op_addr) self.program_counter.value += 1 # log.log(5, "read pc byte: $%02x from $%04x", m, op_addr) return op_addr, m def read_pc_word(self): op_addr = self.program_counter.value m = self.memory.read_word(op_addr) self.program_counter.value += 2 # log.log(5, "\tread pc word: $%04x from $%04x", m, op_addr) return op_addr, m # Op methods: @opcode( 0x10, # PAGE 2 instructions 0x11, # PAGE 3 instructions ) def instruction_PAGE(self, opcode): """ call op from page 2 or 3 """ op_address, opcode2 = self.read_pc_byte() paged_opcode = opcode * 256 + opcode2 # log.debug("$%x *** call paged opcode $%x" % ( # self.program_counter, paged_opcode # )) self.call_instruction_func(op_address - 1, paged_opcode) @opcode( # Add B accumulator to X (unsigned) 0x3a, # ABX (inherent) ) def instruction_ABX(self, opcode): """ Add the 8-bit unsigned value in accumulator B into index register X. source code forms: ABX CC bits "HNZVC": ----- """ self.index_x.increment(self.accu_b.value) @opcode( # Add memory to accumulator with carry 0x89, 0x99, 0xa9, 0xb9, # ADCA (immediate, direct, indexed, extended) 0xc9, 0xd9, 0xe9, 0xf9, # ADCB (immediate, direct, indexed, extended) ) def instruction_ADC(self, opcode, m, register): """ Adds the contents of the C (carry) bit and the memory byte into an 8-bit accumulator. source code forms: ADCA P; ADCB P CC bits "HNZVC": aaaaa """ a = register.value r = a + m + self.C register.set(r) # log.debug("$%x %02x ADC %s: %i + %i + %i = %i (=$%x)" % ( # self.program_counter, opcode, register.name, # a, m, self.C, r, r # )) self.clear_HNZVC() self.update_HNZVC_8(a, m, r) @opcode( # Add memory to D accumulator 0xc3, 0xd3, 0xe3, 0xf3, # ADDD (immediate, direct, indexed, extended) ) def instruction_ADD16(self, opcode, m, register): """ Adds the 16-bit memory value into the 16-bit accumulator source code forms: ADDD P CC bits "HNZVC": -aaaa """ assert register.WIDTH == 16 old = register.value r = old + m register.set(r) # log.debug("$%x %02x %02x ADD16 %s: $%02x + $%02x = $%02x" % ( # self.program_counter, opcode, m, # register.name, # old, m, r # )) self.clear_NZVC() self.update_NZVC_16(old, m, r) @opcode( # Add memory to accumulator 0x8b, 0x9b, 0xab, 0xbb, # ADDA (immediate, direct, indexed, extended) 0xcb, 0xdb, 0xeb, 0xfb, # ADDB (immediate, direct, indexed, extended) ) def instruction_ADD8(self, opcode, m, register): """ Adds the memory byte into an 8-bit accumulator. source code forms: ADDA P; ADDB P CC bits "HNZVC": aaaaa """ assert register.WIDTH == 8 old = register.value r = old + m register.set(r) # log.debug("$%x %02x %02x ADD8 %s: $%02x + $%02x = $%02x" % ( # self.program_counter, opcode, m, # register.name, # old, m, r # )) self.clear_HNZVC() self.update_HNZVC_8(old, m, r) @opcode(0xf, 0x6f, 0x7f) # CLR (direct, indexed, extended) def instruction_CLR_memory(self, opcode, ea): """ Clear memory location source code forms: CLR CC bits "HNZVC": -0100 """ self.update_0100() return ea, 0x00 @opcode(0x4f, 0x5f) # CLRA / CLRB (inherent) def instruction_CLR_register(self, opcode, register): """ Clear accumulator A or B source code forms: CLRA; CLRB CC bits "HNZVC": -0100 """ register.set(0x00) self.update_0100() def COM(self, value): """ CC bits "HNZVC": -aa01 """ value = ~value # the bits of m inverted self.clear_NZ() self.update_NZ01_8(value) return value @opcode( # Complement memory location 0x3, 0x63, 0x73, # COM (direct, indexed, extended) ) def instruction_COM_memory(self, opcode, ea, m): """ Replaces the contents of memory location M with its logical complement. source code forms: COM Q """ r = self.COM(value=m) # log.debug("$%x COM memory $%x to $%x" % ( # self.program_counter, m, r, # )) return ea, r & 0xff @opcode( # Complement accumulator 0x43, # COMA (inherent) 0x53, # COMB (inherent) ) def instruction_COM_register(self, opcode, register): """ Replaces the contents of accumulator A or B with its logical complement. source code forms: COMA; COMB """ register.set(self.COM(value=register.value)) # log.debug("$%x COM %s" % ( # self.program_counter, register.name, # )) @opcode( # Decimal adjust A accumulator 0x19, # DAA (inherent) ) def instruction_DAA(self, opcode): """ The sequence of a single-byte add instruction on accumulator A (either ADDA or ADCA) and a following decimal addition adjust instruction results in a BCD addition with an appropriate carry bit. Both values to be added must be in proper BCD form (each nibble such that: 0 <= nibble <= 9). Multiple-precision addition must add the carry generated by this decimal addition adjust into the next higher digit during the add operation (ADCA) immediately prior to the next decimal addition adjust. source code forms: DAA CC bits "HNZVC": -aa0a Operation: ACCA' ← ACCA + CF(MSN):CF(LSN) where CF is a Correction Factor, as follows: the CF for each nibble (BCD) digit is determined separately, and is either 6 or 0. Least Significant Nibble CF(LSN) = 6 IFF 1) C = 1 or 2) LSN > 9 Most Significant Nibble CF(MSN) = 6 IFF 1) C = 1 or 2) MSN > 9 or 3) MSN > 8 and LSN > 9 Condition Codes: H - Not affected. N - Set if the result is negative; cleared otherwise. Z - Set if the result is zero; cleared otherwise. V - Undefined. C - Set if a carry is generated or if the carry bit was set before the operation; cleared otherwise. """ a = self.accu_a.value correction_factor = 0 a_hi = a & 0xf0 # MSN - Most Significant Nibble a_lo = a & 0x0f # LSN - Least Significant Nibble if a_lo > 0x09 or self.H: # cc & 0x20: correction_factor |= 0x06 if a_hi > 0x80 and a_lo > 0x09: correction_factor |= 0x60 if a_hi > 0x90 or self.C: # cc & 0x01: correction_factor |= 0x60 new_value = correction_factor + a self.accu_a.set(new_value) self.clear_NZ() # V is undefined self.update_NZC_8(new_value) def DEC(self, a): """ Subtract one from the register. The carry bit is not affected, thus allowing this instruction to be used as a loop counter in multiple- precision computations. When operating on unsigned values, only BEQ and BNE branches can be expected to behave consistently. When operating on twos complement values, all signed branches are available. source code forms: DEC Q; DECA; DECB CC bits "HNZVC": -aaa- """ r = a - 1 self.clear_NZV() self.update_NZ_8(r) if r == 0x7f: self.V = 1 return r @opcode(0xa, 0x6a, 0x7a) # DEC (direct, indexed, extended) def instruction_DEC_memory(self, opcode, ea, m): """ Decrement memory location """ r = self.DEC(m) # log.debug("$%x DEC memory value $%x -1 = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) # )) return ea, r & 0xff @opcode(0x4a, 0x5a) # DECA / DECB (inherent) def instruction_DEC_register(self, opcode, register): """ Decrement accumulator """ a = register.value r = self.DEC(a) # log.debug("$%x DEC %s value $%x -1 = $%x" % ( # self.program_counter, # register.name, a, r # )) register.set(r) def INC(self, a): r = a + 1 self.clear_NZV() self.update_NZ_8(r) if r == 0x80: self.V = 1 return r @opcode( # Increment accumulator 0x4c, # INCA (inherent) 0x5c, # INCB (inherent) ) def instruction_INC_register(self, opcode, register): """ Adds to the register. The carry bit is not affected, thus allowing this instruction to be used as a loop counter in multiple-precision computations. When operating on unsigned values, only the BEQ and BNE branches can be expected to behave consistently. When operating on twos complement values, all signed branches are correctly available. source code forms: INC Q; INCA; INCB CC bits "HNZVC": -aaa- """ a = register.value r = self.INC(a) r = register.set(r) @opcode( # Increment memory location 0xc, 0x6c, 0x7c, # INC (direct, indexed, extended) ) def instruction_INC_memory(self, opcode, ea, m): """ Adds to the register. The carry bit is not affected, thus allowing this instruction to be used as a loop counter in multiple-precision computations. When operating on unsigned values, only the BEQ and BNE branches can be expected to behave consistently. When operating on twos complement values, all signed branches are correctly available. source code forms: INC Q; INCA; INCB CC bits "HNZVC": -aaa- """ r = self.INC(m) return ea, r & 0xff @opcode( # Load effective address into an indexable register 0x32, # LEAS (indexed) 0x33, # LEAU (indexed) ) def instruction_LEA_pointer(self, opcode, ea, register): """ Calculates the effective address from the indexed addressing mode and places the address in an indexable register. LEAU and LEAS do not affect the Z bit to allow cleaning up the stack while returning the Z bit as a parameter to a calling routine, and also for MC6800 INS/DES compatibility. LEAU -10,U U-10 -> U Subtracts 10 from U LEAS -10,S S-10 -> S Used to reserve area on stack LEAS 10,S S+10 -> S Used to 'clean up' stack LEAX 5,S S+5 -> X Transfers as well as adds source code forms: LEAS, LEAU CC bits "HNZVC": ----- """ # log.debug( # "$%04x LEA %s: Set %s to $%04x \t| %s" % ( # self.program_counter, # register.name, register.name, ea, # self.cfg.mem_info.get_shortest(ea) # )) register.set(ea) @opcode( # Load effective address into an indexable register 0x30, # LEAX (indexed) 0x31, # LEAY (indexed) ) def instruction_LEA_register(self, opcode, ea, register): """ see instruction_LEA_pointer LEAX and LEAY affect the Z (zero) bit to allow use of these registers as counters and for MC6800 INX/DEX compatibility. LEAX 10,X X+10 -> X Adds 5-bit constant 10 to X LEAX 500,X X+500 -> X Adds 16-bit constant 500 to X LEAY A,Y Y+A -> Y Adds 8-bit accumulator to Y LEAY D,Y Y+D -> Y Adds 16-bit D accumulator to Y source code forms: LEAX, LEAY CC bits "HNZVC": --a-- """ # log.debug("$%04x LEA %s: Set %s to $%04x \t| %s" % ( # self.program_counter, # register.name, register.name, ea, # self.cfg.mem_info.get_shortest(ea) # )) register.set(ea) self.Z = 0 self.set_Z16(ea) @opcode( # Unsigned multiply (A * B ? D) 0x3d, # MUL (inherent) ) def instruction_MUL(self, opcode): """ Multiply the unsigned binary numbers in the accumulators and place the result in both accumulators (ACCA contains the most-significant byte of the result). Unsigned multiply allows multiple-precision operations. The C (carry) bit allows rounding the most-significant byte through the sequence: MUL, ADCA #0. source code forms: MUL CC bits "HNZVC": --a-a """ r = self.accu_a.value * self.accu_b.value self.accu_d.set(r) self.Z = 1 if r == 0 else 0 self.C = 1 if r & 0x80 else 0 @opcode( # Negate accumulator 0x40, # NEGA (inherent) 0x50, # NEGB (inherent) ) def instruction_NEG_register(self, opcode, register): """ Replaces the register with its twos complement. The C (carry) bit represents a borrow and is set to the inverse of the resulting binary carry. Note that 80 16 is replaced by itself and only in this case is the V (overflow) bit set. The value 00 16 is also replaced by itself, and only in this case is the C (carry) bit cleared. source code forms: NEG Q; NEGA; NEG B CC bits "HNZVC": uaaaa """ x = register.value r = x * -1 # same as: r = ~x + 1 register.set(r) # log.debug("$%04x NEG %s $%02x to $%02x" % ( # self.program_counter, register.name, x, r, # )) self.clear_NZVC() self.update_NZVC_8(0, x, r) _wrong_NEG = 0 @opcode(0x0, 0x60, 0x70) # NEG (direct, indexed, extended) def instruction_NEG_memory(self, opcode, ea, m): """ Negate memory """ if opcode == 0x0 and ea == 0x0 and m == 0x0: self._wrong_NEG += 1 if self._wrong_NEG > 10: raise RuntimeError("Wrong PC ???") else: self._wrong_NEG = 0 r = m * -1 # same as: r = ~m + 1 # log.debug("$%04x NEG $%02x from %04x to $%02x" % ( # self.program_counter, m, ea, r, # )) self.clear_NZVC() self.update_NZVC_8(0, m, r) return ea, r & 0xff @opcode(0x12) # NOP (inherent) def instruction_NOP(self, opcode): """ No operation source code forms: NOP CC bits "HNZVC": ----- """ # log.debug("\tNOP") @opcode( # Subtract memory from accumulator with borrow 0x82, 0x92, 0xa2, 0xb2, # SBCA (immediate, direct, indexed, extended) 0xc2, 0xd2, 0xe2, 0xf2, # SBCB (immediate, direct, indexed, extended) ) def instruction_SBC(self, opcode, m, register): """ Subtracts the contents of memory location M and the borrow (in the C (carry) bit) from the contents of the designated 8-bit register, and places the result in that register. The C bit represents a borrow and is set to the inverse of the resulting binary carry. source code forms: SBCA P; SBCB P CC bits "HNZVC": uaaaa """ a = register.value r = a - m - self.C register.set(r) # log.debug("$%x %02x SBC %s: %i - %i - %i = %i (=$%x)" % ( # self.program_counter, opcode, register.name, # a, m, self.C, r, r # )) self.clear_NZVC() self.update_NZVC_8(a, m, r) @opcode( # Sign Extend B accumulator into A accumulator 0x1d, # SEX (inherent) ) def instruction_SEX(self, opcode): """ This instruction transforms a twos complement 8-bit value in accumulator B into a twos complement 16-bit value in the D accumulator. source code forms: SEX CC bits "HNZVC": -aa0- // 0x1d SEX inherent case 0x1d: WREG_A = (RREG_B & 0x80) ? 0xff : 0; CLR_NZ; SET_NZ16(REG_D); peek_byte(cpu, REG_PC); #define SIGNED(b) ((Word)(b&0x80?b|0xff00:b)) case 0x1D: /* SEX */ tw=SIGNED(ibreg); SETNZ16(tw) SETDREG(tw) break; """ b = self.accu_b.value if b & 0x80 == 0: self.accu_a.set(0x00) d = self.accu_d.value # log.debug("SEX: b=$%x ; $%x&0x80=$%x ; d=$%x", b, b, (b & 0x80), d) self.clear_NZ() self.update_NZ_16(d) @opcode( # Subtract memory from accumulator 0x80, 0x90, 0xa0, 0xb0, # SUBA (immediate, direct, indexed, extended) 0xc0, 0xd0, 0xe0, 0xf0, # SUBB (immediate, direct, indexed, extended) 0x83, 0x93, 0xa3, 0xb3, # SUBD (immediate, direct, indexed, extended) ) def instruction_SUB(self, opcode, m, register): """ Subtracts the value in memory location M from the contents of a register. The C (carry) bit represents a borrow and is set to the inverse of the resulting binary carry. source code forms: SUBA P; SUBB P; SUBD P CC bits "HNZVC": uaaaa """ r = register.value r_new = r - m register.set(r_new) # log.debug("$%x SUB8 %s: $%x - $%x = $%x (dez.: %i - %i = %i)" % ( # self.program_counter, register.name, # r, m, r_new, # r, m, r_new, # )) self.clear_NZVC() if register.WIDTH == 8: self.update_NZVC_8(r, m, r_new) else: assert register.WIDTH == 16 self.update_NZVC_16(r, m, r_new) # ---- Register Changes - FIXME: Better name for this section?!? ---- REGISTER_BIT2STR = { 0x0: REG_D, # 0000 - 16 bit concatenated reg.(A B) 0x1: REG_X, # 0001 - 16 bit index register 0x2: REG_Y, # 0010 - 16 bit index register 0x3: REG_U, # 0011 - 16 bit user-stack pointer 0x4: REG_S, # 0100 - 16 bit system-stack pointer 0x5: REG_PC, # 0101 - 16 bit program counter register 0x6: undefined_reg.name, # undefined 0x7: undefined_reg.name, # undefined 0x8: REG_A, # 1000 - 8 bit accumulator 0x9: REG_B, # 1001 - 8 bit accumulator 0xa: REG_CC, # 1010 - 8 bit condition code register as flags 0xb: REG_DP, # 1011 - 8 bit direct page register 0xc: undefined_reg.name, # undefined 0xd: undefined_reg.name, # undefined 0xe: undefined_reg.name, # undefined 0xf: undefined_reg.name, # undefined } def _get_register_obj(self, addr): addr_str = self.REGISTER_BIT2STR[addr] reg_obj = self.register_str2object[addr_str] # log.debug("get register obj: addr: $%x addr_str: %s -> register: %s" % ( # addr, addr_str, reg_obj.name # )) # log.debug(repr(self.register_str2object)) return reg_obj def _get_register_and_value(self, addr): reg = self._get_register_obj(addr) reg_value = reg.value return reg, reg_value @opcode(0x1f) # TFR (immediate) def instruction_TFR(self, opcode, m): """ source code forms: TFR R1, R2 CC bits "HNZVC": ccccc """ high, low = divmod(m, 16) dst_reg = self._get_register_obj(low) src_reg = self._get_register_obj(high) src_value = convert_differend_width(src_reg, dst_reg) dst_reg.set(src_value) # log.debug("\tTFR: Set %s to $%x from %s", # dst_reg, src_value, src_reg.name # ) @opcode( # Exchange R1 with R2 0x1e, # EXG (immediate) ) def instruction_EXG(self, opcode, m): """ source code forms: EXG R1,R2 CC bits "HNZVC": ccccc """ high, low = divmod(m, 0x10) reg1 = self._get_register_obj(high) reg2 = self._get_register_obj(low) new_reg1_value = convert_differend_width(reg2, reg1) new_reg2_value = convert_differend_width(reg1, reg2) reg1.set(new_reg1_value) reg2.set(new_reg2_value)
class CPUBase: def __init__(self, memory, cfg): pass def get_state(self): ''' used in unittests ''' pass def set_state(self, state): ''' used in unittests ''' pass def reset(self): pass def get_and_call_next_op(self): pass def quit(self): pass def call_instruction_func(self, op_address, opcode): pass def add_sync_callback(self, callback_cycles, callback): ''' Add a CPU cycle triggered callback ''' pass def call_sync_callbacks(self): ''' Call every sync callback with CPU cycles trigger ''' pass def burst_run(self): ''' Run CPU as fast as Python can... ''' pass def run(self, max_run_time=0.1, target_cycles_per_sec=None): pass def test_run(self, start, end, max_ops=1000000): pass def test_run2(self, start, count): pass @property def get_info(self): pass def read_pc_byte(self): pass def read_pc_word(self): pass @opcode( 0x10, # PAGE 2 instructions 0x11, # PAGE 3 instructions ) def instruction_PAGE(self, opcode): ''' call op from page 2 or 3 ''' pass @opcode( # Add B accumulator to X (unsigned) 0x3a, # ABX (inherent) ) def instruction_ABX(self, opcode): ''' Add the 8-bit unsigned value in accumulator B into index register X. source code forms: ABX CC bits "HNZVC": ----- ''' pass @opcode( # Add memory to accumulator with carry 0x89, 0x99, 0xa9, 0xb9, # ADCA (immediate, direct, indexed, extended) 0xc9, 0xd9, 0xe9, 0xf9, # ADCB (immediate, direct, indexed, extended) ) def instruction_ADC(self, opcode, m, register): ''' Adds the contents of the C (carry) bit and the memory byte into an 8-bit accumulator. source code forms: ADCA P; ADCB P CC bits "HNZVC": aaaaa ''' pass @opcode( # Add memory to D accumulator 0xc3, 0xd3, 0xe3, 0xf3, # ADDD (immediate, direct, indexed, extended) ) def instruction_ADD16(self, opcode, m, register): ''' Adds the 16-bit memory value into the 16-bit accumulator source code forms: ADDD P CC bits "HNZVC": -aaaa ''' pass @opcode( # Add memory to accumulator 0x8b, 0x9b, 0xab, 0xbb, # ADDA (immediate, direct, indexed, extended) 0xcb, 0xdb, 0xeb, 0xfb, # ADDB (immediate, direct, indexed, extended) ) def instruction_ADD8(self, opcode, m, register): ''' Adds the memory byte into an 8-bit accumulator. source code forms: ADDA P; ADDB P CC bits "HNZVC": aaaaa ''' pass @opcode(0xf, 0x6f, 0x7f) def instruction_CLR_memory(self, opcode, ea): ''' Clear memory location source code forms: CLR CC bits "HNZVC": -0100 ''' pass @opcode(0x4f, 0x5f) def instruction_CLR_register(self, opcode, register): ''' Clear accumulator A or B source code forms: CLRA; CLRB CC bits "HNZVC": -0100 ''' pass def COM(self, value): ''' CC bits "HNZVC": -aa01 ''' pass @opcode( # Complement memory location 0x3, 0x63, 0x73, # COM (direct, indexed, extended) ) def instruction_COM_memory(self, opcode, ea, m): ''' Replaces the contents of memory location M with its logical complement. source code forms: COM Q ''' pass @opcode( # Complement accumulator 0x43, # COMA (inherent) 0x53, # COMB (inherent) ) def instruction_COM_register(self, opcode, register): ''' Replaces the contents of accumulator A or B with its logical complement. source code forms: COMA; COMB ''' pass @opcode( # Decimal adjust A accumulator 0x19, # DAA (inherent) ) def instruction_DAA(self, opcode): ''' The sequence of a single-byte add instruction on accumulator A (either ADDA or ADCA) and a following decimal addition adjust instruction results in a BCD addition with an appropriate carry bit. Both values to be added must be in proper BCD form (each nibble such that: 0 <= nibble <= 9). Multiple-precision addition must add the carry generated by this decimal addition adjust into the next higher digit during the add operation (ADCA) immediately prior to the next decimal addition adjust. source code forms: DAA CC bits "HNZVC": -aa0a Operation: ACCA' ← ACCA + CF(MSN):CF(LSN) where CF is a Correction Factor, as follows: the CF for each nibble (BCD) digit is determined separately, and is either 6 or 0. Least Significant Nibble CF(LSN) = 6 IFF 1) C = 1 or 2) LSN > 9 Most Significant Nibble CF(MSN) = 6 IFF 1) C = 1 or 2) MSN > 9 or 3) MSN > 8 and LSN > 9 Condition Codes: H - Not affected. N - Set if the result is negative; cleared otherwise. Z - Set if the result is zero; cleared otherwise. V - Undefined. C - Set if a carry is generated or if the carry bit was set before the operation; cleared otherwise. ''' pass def DEC(self, a): ''' Subtract one from the register. The carry bit is not affected, thus allowing this instruction to be used as a loop counter in multiple- precision computations. When operating on unsigned values, only BEQ and BNE branches can be expected to behave consistently. When operating on twos complement values, all signed branches are available. source code forms: DEC Q; DECA; DECB CC bits "HNZVC": -aaa- ''' pass @opcode(0xa, 0x6a, 0x7a) def instruction_DEC_memory(self, opcode, ea, m): ''' Decrement memory location ''' pass @opcode(0x4a, 0x5a) def instruction_DEC_register(self, opcode, register): ''' Decrement accumulator ''' pass def INC(self, a): pass @opcode( # Increment accumulator 0x4c, # INCA (inherent) 0x5c, # INCB (inherent) ) def instruction_INC_register(self, opcode, register): ''' Adds to the register. The carry bit is not affected, thus allowing this instruction to be used as a loop counter in multiple-precision computations. When operating on unsigned values, only the BEQ and BNE branches can be expected to behave consistently. When operating on twos complement values, all signed branches are correctly available. source code forms: INC Q; INCA; INCB CC bits "HNZVC": -aaa- ''' pass @opcode( # Increment memory location 0xc, 0x6c, 0x7c, # INC (direct, indexed, extended) ) def instruction_INC_memory(self, opcode, ea, m): ''' Adds to the register. The carry bit is not affected, thus allowing this instruction to be used as a loop counter in multiple-precision computations. When operating on unsigned values, only the BEQ and BNE branches can be expected to behave consistently. When operating on twos complement values, all signed branches are correctly available. source code forms: INC Q; INCA; INCB CC bits "HNZVC": -aaa- ''' pass @opcode( # Load effective address into an indexable register 0x32, # LEAS (indexed) 0x33, # LEAU (indexed) ) def instruction_LEA_pointer(self, opcode, ea, register): ''' Calculates the effective address from the indexed addressing mode and places the address in an indexable register. LEAU and LEAS do not affect the Z bit to allow cleaning up the stack while returning the Z bit as a parameter to a calling routine, and also for MC6800 INS/DES compatibility. LEAU -10,U U-10 -> U Subtracts 10 from U LEAS -10,S S-10 -> S Used to reserve area on stack LEAS 10,S S+10 -> S Used to 'clean up' stack LEAX 5,S S+5 -> X Transfers as well as adds source code forms: LEAS, LEAU CC bits "HNZVC": ----- ''' pass @opcode( # Load effective address into an indexable register 0x30, # LEAX (indexed) 0x31, # LEAY (indexed) ) def instruction_LEA_register(self, opcode, ea, register): ''' see instruction_LEA_pointer LEAX and LEAY affect the Z (zero) bit to allow use of these registers as counters and for MC6800 INX/DEX compatibility. LEAX 10,X X+10 -> X Adds 5-bit constant 10 to X LEAX 500,X X+500 -> X Adds 16-bit constant 500 to X LEAY A,Y Y+A -> Y Adds 8-bit accumulator to Y LEAY D,Y Y+D -> Y Adds 16-bit D accumulator to Y source code forms: LEAX, LEAY CC bits "HNZVC": --a-- ''' pass @opcode( # Unsigned multiply (A * B ? D) 0x3d, # MUL (inherent) ) def instruction_MUL(self, opcode): ''' Multiply the unsigned binary numbers in the accumulators and place the result in both accumulators (ACCA contains the most-significant byte of the result). Unsigned multiply allows multiple-precision operations. The C (carry) bit allows rounding the most-significant byte through the sequence: MUL, ADCA #0. source code forms: MUL CC bits "HNZVC": --a-a ''' pass @opcode( # Negate accumulator 0x40, # NEGA (inherent) 0x50, # NEGB (inherent) ) def instruction_NEG_register(self, opcode, register): ''' Replaces the register with its twos complement. The C (carry) bit represents a borrow and is set to the inverse of the resulting binary carry. Note that 80 16 is replaced by itself and only in this case is the V (overflow) bit set. The value 00 16 is also replaced by itself, and only in this case is the C (carry) bit cleared. source code forms: NEG Q; NEGA; NEG B CC bits "HNZVC": uaaaa ''' pass @opcode(0x0, 0x60, 0x70) def instruction_NEG_memory(self, opcode, ea, m): ''' Negate memory ''' pass @opcode(0x12) def instruction_NOP(self, opcode): ''' No operation source code forms: NOP CC bits "HNZVC": ----- ''' pass @opcode( # Subtract memory from accumulator with borrow 0x82, 0x92, 0xa2, 0xb2, # SBCA (immediate, direct, indexed, extended) 0xc2, 0xd2, 0xe2, 0xf2, # SBCB (immediate, direct, indexed, extended) ) def instruction_SBC(self, opcode, m, register): ''' Subtracts the contents of memory location M and the borrow (in the C (carry) bit) from the contents of the designated 8-bit register, and places the result in that register. The C bit represents a borrow and is set to the inverse of the resulting binary carry. source code forms: SBCA P; SBCB P CC bits "HNZVC": uaaaa ''' pass @opcode( # Sign Extend B accumulator into A accumulator 0x1d, # SEX (inherent) ) def instruction_SEX(self, opcode): ''' This instruction transforms a twos complement 8-bit value in accumulator B into a twos complement 16-bit value in the D accumulator. source code forms: SEX CC bits "HNZVC": -aa0- // 0x1d SEX inherent case 0x1d: WREG_A = (RREG_B & 0x80) ? 0xff : 0; CLR_NZ; SET_NZ16(REG_D); peek_byte(cpu, REG_PC); #define SIGNED(b) ((Word)(b&0x80?b|0xff00:b)) case 0x1D: /* SEX */ tw=SIGNED(ibreg); SETNZ16(tw) SETDREG(tw) break; ''' pass @opcode( # Subtract memory from accumulator 0x80, 0x90, 0xa0, 0xb0, # SUBA (immediate, direct, indexed, extended) 0xc0, 0xd0, 0xe0, 0xf0, # SUBB (immediate, direct, indexed, extended) 0x83, 0x93, 0xa3, 0xb3, # SUBD (immediate, direct, indexed, extended) ) def instruction_SUB(self, opcode, m, register): ''' Subtracts the value in memory location M from the contents of a register. The C (carry) bit represents a borrow and is set to the inverse of the resulting binary carry. source code forms: SUBA P; SUBB P; SUBD P CC bits "HNZVC": uaaaa ''' pass def _get_register_obj(self, addr): pass def _get_register_and_value(self, addr): pass @opcode(0x1f) def instruction_TFR(self, opcode, m): ''' source code forms: TFR R1, R2 CC bits "HNZVC": ccccc ''' pass @opcode( # Exchange R1 with R2 0x1e, # EXG (immediate) ) def instruction_EXG(self, opcode, m): ''' source code forms: EXG R1,R2 CC bits "HNZVC": ccccc ''' pass
73
32
16
2
7
7
1
0.95
0
9
4
1
46
22
46
46
907
165
427
223
307
404
296
150
249
4
0
2
68
1,385
6809/MC6809
6809_MC6809/MC6809/components/cpu_utils/MC6809_registers.py
MC6809.components.cpu_utils.MC6809_registers.UndefinedRegister
class UndefinedRegister(ValueStorageBase): # used in TFR and EXG WIDTH = 16 # 16 Bit name = "undefined!" value = 0xffff def __init__(self): pass def set(self, v): log.warning("Set value to 'undefined' register!") def get(self): return 0xffff
class UndefinedRegister(ValueStorageBase): def __init__(self): pass def set(self, v): pass def get(self): pass
4
0
2
0
2
0
1
0.2
1
0
0
0
3
0
3
8
14
3
10
7
6
2
10
7
6
1
1
0
3
1,386
6809/MC6809
6809_MC6809/MC6809/components/cpu6809.py
MC6809.components.cpu6809.CPU
class CPU(CPUBase, AddressingMixin, StackMixin, InterruptMixin, OpsLoadStoreMixin, OpsBranchesMixin, OpsTestMixin, OpsLogicalMixin, CPUConditionCodeRegisterMixin, CPUThreadedStatusMixin): def to_speed_limit(self): return change_cpu(self, CPUSpeedLimit)
class CPU(CPUBase, AddressingMixin, StackMixin, InterruptMixin, OpsLoadStoreMixin, OpsBranchesMixin, OpsTestMixin, OpsLogicalMixin, CPUConditionCodeRegisterMixin, CPUThreadedStatusMixin): def to_speed_limit(self): pass
2
0
2
0
2
0
1
0
10
1
1
3
1
0
1
156
5
1
4
3
1
0
3
2
1
1
1
0
1
1,387
6809/MC6809
6809_MC6809/MC6809/components/cpu6809.py
MC6809.components.cpu6809.CPUControlServer
class CPUControlServer(CPUControlServerMixin, CPU): pass
class CPUControlServer(CPUControlServerMixin, CPU): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
157
2
0
2
1
1
0
2
1
1
0
2
0
0
1,388
6809/MC6809
6809_MC6809/MC6809/components/cpu6809.py
MC6809.components.cpu6809.CPUSpeedLimit
class CPUSpeedLimit(CPUSpeedLimitMixin, CPU): def to_normal(self): return change_cpu(self, CPU)
class CPUSpeedLimit(CPUSpeedLimitMixin, CPU): def to_normal(self): pass
2
0
2
0
2
0
1
0
2
0
0
0
1
0
1
158
4
1
3
2
1
0
3
2
1
1
2
0
1
1,389
6809/MC6809
6809_MC6809/MC6809/components/cpu_utils/MC6809_registers.py
MC6809.components.cpu_utils.MC6809_registers.ValueStorage8Bit
class ValueStorage8Bit(ValueStorageBase): WIDTH = 8 # 8 Bit def set(self, v): if v > 0xff: # log.info(" **** Value $%x is to big for %s (8-bit)", v, self.name) v = v & 0xff # log.info(" ^^^^ Value %s (8-bit) wrap around to $%x", self.name, v) elif v < 0: # log.info(" **** %s value $%x is negative", self.name, v) v = 0x100 + v # log.info(" **** Value %s (8-bit) wrap around to $%x", self.name, v) self.value = v def __str__(self): return f"{self.name}={self.value:02x}"
class ValueStorage8Bit(ValueStorageBase): def set(self, v): pass def __str__(self): pass
3
0
6
0
4
2
2
0.5
1
0
0
0
2
1
2
7
16
2
10
5
7
5
9
5
6
3
1
1
4
1,390
6809/MC6809
6809_MC6809/MC6809/components/cpu6809.py
MC6809.components.cpu6809.CPUTypeAssert
class CPUTypeAssert(CPUTypeAssertMixin, CPU): pass
class CPUTypeAssert(CPUTypeAssertMixin, CPU): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
159
2
0
2
1
1
0
2
1
1
0
2
0
0
1,391
6809/MC6809
6809_MC6809/MC6809/components/cpu6809_trace.py
MC6809.components.cpu6809_trace.InstructionTrace
class InstructionTrace(PrepagedInstructions): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cfg = self.cpu.cfg self.get_mem_info = self.cpu.cfg.mem_info.get_shortest self.__origin_instr_func = self.instr_func self.instr_func = self.__call_instr_func # def __getattribute__(self, attr, *args, **kwargs): # if attr not in ("__call", "cpu", "memory", "instr_func"): # return InstructionTrace.__call # print attr, args, kwargs # return PrepagedInstructions.__getattribute__(self, attr, *args, **kwargs) # # def __call(self, func, *args, **kwargs): # print func, args, kwargs # raise def __call_instr_func(self, opcode, *args, **kwargs): # call the op CPU code method result = self.__origin_instr_func(opcode, *args, **kwargs) if opcode in (0x10, 0x11): log.debug("Skip PAGE 2 and PAGE 3 instruction in trace") return op_code_data = MC6809OP_DATA_DICT[opcode] op_address = self.cpu.last_op_address ob_bytes = op_code_data["bytes"] op_bytes = "".join( f"{value:02x}" for __, value in self.cpu.memory.iter_bytes(op_address, op_address + ob_bytes) ) kwargs_info = [] if "register" in kwargs: kwargs_info.append(str(kwargs["register"])) if "ea" in kwargs: kwargs_info.append(f"ea:{kwargs['ea']:04x}") if "m" in kwargs: kwargs_info.append(f"m:{kwargs['m']:x}") msg = "{op_address:04x}| {op_bytes:<11} {mnemonic:<7} {kwargs:<19} {cpu} | {cc} | {mem}\n".format( op_address=op_address, op_bytes=op_bytes, mnemonic=op_code_data["mnemonic"], kwargs=" ".join(kwargs_info), cpu=self.cpu.get_info, cc=self.cpu.get_cc_info(), mem=self.get_mem_info(op_address) ) sys.stdout.write(msg) if not op_bytes.startswith(f"{opcode:02x}"): self.cpu.memory.print_dump(op_address, op_address + ob_bytes) self.cpu.memory.print_dump(op_address - 10, op_address + ob_bytes + 10) assert op_bytes.startswith(f"{opcode:02x}"), f"{op_bytes} doesn't start with {self.opcode:02x}" return result
class InstructionTrace(PrepagedInstructions): def __init__(self, *args, **kwargs): pass def __call_instr_func(self, opcode, *args, **kwargs): pass
3
0
26
5
20
1
4
0.24
1
2
0
0
2
4
2
79
63
12
41
15
38
10
30
14
27
6
2
1
7
1,392
6809/MC6809
6809_MC6809/MC6809/components/cpu_utils/MC6809_registers.py
MC6809.components.cpu_utils.MC6809_registers.ConcatenatedAccumulator
class ConcatenatedAccumulator: """ 6809 has register D - 16 bit concatenated reg. (A + B) """ WIDTH = 16 # 16 Bit def __init__(self, name, a, b): self.name = name self._a = a self._b = b def set(self, value): self._a.set(value >> 8) self._b.set(value & 0xff) @property def value(self): return self._a.value * 256 + self._b.value def __str__(self): return f"{self.name}={self.value:04x}"
class ConcatenatedAccumulator: ''' 6809 has register D - 16 bit concatenated reg. (A + B) ''' def __init__(self, name, a, b): pass def set(self, value): pass @property def value(self): pass def __str__(self): pass
6
1
3
0
3
0
1
0.29
0
0
0
0
4
3
4
4
21
4
14
10
8
4
13
9
8
1
0
0
4
1,393
6809/MC6809
6809_MC6809/MC6809/components/MC6809data/CPU6809_HTML_export.py
MC6809.components.MC6809data.CPU6809_HTML_export.Cell
class Cell: def __init__(self, txt): self.txt = txt self.rowspan = 0 self.headline = None def html(self): if self.rowspan is None: return "" elif self.rowspan == 1: return f"<td>{self.txt}</td>" return f'<td rowspan="{self.rowspan:d}" title="{self.headline}: {self.txt}">{self.txt}</td>' def __str__(self): return f"<'{self.txt}' rowspan={self.rowspan}>" __repr__ = __str__
class Cell: def __init__(self, txt): pass def html(self): pass def __str__(self): pass
4
0
4
0
4
0
2
0
0
0
0
0
3
3
3
3
16
2
14
8
10
0
13
8
9
3
0
1
5
1,394
6809/MC6809
6809_MC6809/MC6809/cli_dev/__init__.py
MC6809.cli_dev.ClickGroup
class ClickGroup(RichGroup): # FIXME: How to set the "info_name" easier? def make_context(self, info_name, *args, **kwargs): info_name = './dev-cli.py' return super().make_context(info_name, *args, **kwargs)
class ClickGroup(RichGroup): def make_context(self, info_name, *args, **kwargs): pass
2
0
3
0
3
0
1
0.25
1
1
0
0
1
0
1
1
4
0
4
2
2
1
4
2
2
1
1
0
1
1,395
6809/MC6809
6809_MC6809/MC6809/cli_app/__init__.py
MC6809.cli_app.ClickGroup
class ClickGroup(RichGroup): # FIXME: How to set the "info_name" easier? def make_context(self, info_name, *args, **kwargs): info_name = './cli.py' return super().make_context(info_name, *args, **kwargs)
class ClickGroup(RichGroup): def make_context(self, info_name, *args, **kwargs): pass
2
0
3
0
3
0
1
0.25
1
1
0
0
1
0
1
1
4
0
4
2
2
1
4
2
2
1
1
0
1
1,396
6809/MC6809
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/6809_MC6809/MC6809/components/mc6809_ops_test.py
MC6809.components.mc6809_ops_test.OpsTestMixin
class OpsTestMixin: # ---- Test Instructions ---- @opcode( # Compare memory from stack pointer # CMPD (immediate, direct, indexed, extended) 0x1083, 0x1093, 0x10a3, 0x10b3, # CMPS (immediate, direct, indexed, extended) 0x118c, 0x119c, 0x11ac, 0x11bc, # CMPU (immediate, direct, indexed, extended) 0x1183, 0x1193, 0x11a3, 0x11b3, 0x8c, 0x9c, 0xac, 0xbc, # CMPX (immediate, direct, indexed, extended) # CMPY (immediate, direct, indexed, extended) 0x108c, 0x109c, 0x10ac, 0x10bc, ) def instruction_CMP16(self, opcode, m, register): """ Compares the 16-bit contents of the concatenated memory locations M:M+1 to the contents of the specified register and sets the appropriate condition codes. Neither the memory locations nor the specified register is modified unless autoincrement or autodecrement are used. The carry flag represents a borrow and is set to the inverse of the resulting binary carry. source code forms: CMPD P; CMPX P; CMPY P; CMPU P; CMPS P CC bits "HNZVC": -aaaa """ r = register.value r_new = r - m # log.warning("$%x CMP16 %s $%x - $%x = $%x" % ( # self.program_counter, # register.name, # r, m, r_new, # )) self.clear_NZVC() self.update_NZVC_16(r, m, r_new) @opcode( # Compare memory from accumulator 0x81, 0x91, 0xa1, 0xb1, # CMPA (immediate, direct, indexed, extended) 0xc1, 0xd1, 0xe1, 0xf1, # CMPB (immediate, direct, indexed, extended) ) def instruction_CMP8(self, opcode, m, register): """ Compares the contents of memory location to the contents of the specified register and sets the appropriate condition codes. Neither memory location M nor the specified register is modified. The carry flag represents a borrow and is set to the inverse of the resulting binary carry. source code forms: CMPA P; CMPB P CC bits "HNZVC": uaaaa """ r = register.value r_new = r - m # log.warning("$%x CMP8 %s $%x - $%x = $%x" % ( # self.program_counter, # register.name, # r, m, r_new, # )) self.clear_NZVC() self.update_NZVC_8(r, m, r_new) @opcode( # Bit test memory with accumulator 0x85, 0x95, 0xa5, 0xb5, # BITA (immediate, direct, indexed, extended) 0xc5, 0xd5, 0xe5, 0xf5, # BITB (immediate, direct, indexed, extended) ) def instruction_BIT(self, opcode, m, register): """ Performs the logical AND of the contents of accumulator A or B and the contents of memory location M and modifies the condition codes accordingly. The contents of accumulator A or B and memory location M are not affected. source code forms: BITA P; BITB P CC bits "HNZVC": -aa0- """ x = register.value r = m & x # log.debug("$%x BIT update CC with $%x (m:%i & %s:%i)" % ( # self.program_counter, # r, m, register.name, x # )) self.clear_NZV() self.update_NZ_8(r) @opcode( # Test accumulator 0x4d, # TSTA (inherent) 0x5d, # TSTB (inherent) ) def instruction_TST_register(self, opcode, register): """ Set the N (negative) and Z (zero) bits according to the contents of accumulator A or B, and clear the V (overflow) bit. The TST instruction provides only minimum information when testing unsigned values; since no unsigned value is less than zero, BLO and BLS have no utility. While BHI could be used after TST, it provides exactly the same control as BNE, which is preferred. The signed branches are available. The MC6800 processor clears the C (carry) bit. source code forms: TST Q; TSTA; TSTB CC bits "HNZVC": -aa0- """ x = register.value self.clear_NZV() self.update_NZ_8(x) @opcode(0xd, 0x6d, 0x7d) # TST (direct, indexed, extended) def instruction_TST_memory(self, opcode, m): """ Test memory location """ # log.debug("$%x TST m=$%02x" % ( # self.program_counter, m # )) self.clear_NZV() self.update_NZ_8(m)
class OpsTestMixin: @opcode( # Compare memory from stack pointer # CMPD (immediate, direct, indexed, extended) 0x1083, 0x1093, 0x10a3, 0x10b3, # CMPS (immediate, direct, indexed, extended) 0x118c, 0x119c, 0x11ac, 0x11bc, # CMPU (immediate, direct, indexed, extended) 0x1183, 0x1193, 0x11a3, 0x11b3, 0x8c, 0x9c, 0xac, 0xbc, # CMPX (immediate, direct, indexed, extended) # CMPY (immediate, direct, indexed, extended) 0x108c, 0x109c, 0x10ac, 0x10bc, ) def instruction_CMP16(self, opcode, m, register): ''' Compares the 16-bit contents of the concatenated memory locations M:M+1 to the contents of the specified register and sets the appropriate condition codes. Neither the memory locations nor the specified register is modified unless autoincrement or autodecrement are used. The carry flag represents a borrow and is set to the inverse of the resulting binary carry. source code forms: CMPD P; CMPX P; CMPY P; CMPU P; CMPS P CC bits "HNZVC": -aaaa ''' pass @opcode( # Compare memory from accumulator 0x81, 0x91, 0xa1, 0xb1, # CMPA (immediate, direct, indexed, extended) 0xc1, 0xd1, 0xe1, 0xf1, # CMPB (immediate, direct, indexed, extended) ) def instruction_CMP8(self, opcode, m, register): ''' Compares the contents of memory location to the contents of the specified register and sets the appropriate condition codes. Neither memory location M nor the specified register is modified. The carry flag represents a borrow and is set to the inverse of the resulting binary carry. source code forms: CMPA P; CMPB P CC bits "HNZVC": uaaaa ''' pass @opcode( # Bit test memory with accumulator 0x85, 0x95, 0xa5, 0xb5, # BITA (immediate, direct, indexed, extended) 0xc5, 0xd5, 0xe5, 0xf5, # BITB (immediate, direct, indexed, extended) ) def instruction_BIT(self, opcode, m, register): ''' Performs the logical AND of the contents of accumulator A or B and the contents of memory location M and modifies the condition codes accordingly. The contents of accumulator A or B and memory location M are not affected. source code forms: BITA P; BITB P CC bits "HNZVC": -aa0- ''' pass @opcode( # Test accumulator 0x4d, # TSTA (inherent) 0x5d, # TSTB (inherent) ) def instruction_TST_register(self, opcode, register): ''' Set the N (negative) and Z (zero) bits according to the contents of accumulator A or B, and clear the V (overflow) bit. The TST instruction provides only minimum information when testing unsigned values; since no unsigned value is less than zero, BLO and BLS have no utility. While BHI could be used after TST, it provides exactly the same control as BNE, which is preferred. The signed branches are available. The MC6800 processor clears the C (carry) bit. source code forms: TST Q; TSTA; TSTB CC bits "HNZVC": -aa0- ''' pass @opcode(0xd, 0x6d, 0x7d) def instruction_TST_memory(self, opcode, m): ''' Test memory location ''' pass
11
5
17
2
4
11
1
1.7
0
0
0
1
5
0
5
5
115
15
43
33
17
73
23
13
17
1
0
0
5
1,397
6809/MC6809
6809_MC6809/MC6809/tests/test_6809_register_changes.py
MC6809.tests.test_6809_register_changes.Test6809_TFR
class Test6809_TFR(BaseCPUTestCase): def test_TFR_A_B(self): self.cpu.accu_a.set(0x12) self.cpu.accu_b.set(0x34) self.cpu_test_run(start=0x2000, end=None, mem=[ 0x1F, 0x89, # TFR A,B ]) self.assertEqualHexByte(self.cpu.accu_a.value, 0x12) self.assertEqualHexByte(self.cpu.accu_b.value, 0x12) def test_TFR_B_A(self): self.cpu.accu_a.set(0x12) self.cpu.accu_b.set(0x34) self.cpu_test_run(start=0x2000, end=None, mem=[ 0x1F, 0x98, # TFR B,A ]) self.assertEqualHexByte(self.cpu.accu_a.value, 0x34) self.assertEqualHexByte(self.cpu.accu_b.value, 0x34) def test_TFR_X_U(self): """ LDX #$1234 LDU #$abcd TFR X,U STX $20 STU $30 """ self.cpu.index_x.set(0x1234) self.cpu.user_stack_pointer.set(0xabcd) self.cpu_test_run(start=0x2000, end=None, mem=[ 0x1F, 0x13, # TFR X,U ]) self.assertEqualHexWord(self.cpu.index_x.value, 0x1234) self.assertEqualHexWord(self.cpu.user_stack_pointer.value, 0x1234) def test_TFR_CC_X(self): """ transfer 8 bit register in a 16 bit register TODO: verify this behaviour on real hardware! """ self.cpu.set_cc(0x34) self.cpu_test_run(start=0x4000, end=None, mem=[ 0x1F, 0xA1, # TFR CC,X ]) self.assertEqualHexByte(self.cpu.get_cc_value(), 0x34) self.assertEqualHexWord(self.cpu.index_x.value, 0xff34) def test_TFR_CC_A(self): """ transfer 8 bit register in a 16 bit register TODO: verify this behaviour on real hardware! """ self.cpu.accu_a.set(0xab) self.cpu.set_cc(0x89) self.cpu_test_run(start=0x4000, end=None, mem=[ 0x1F, 0xA8, # TFR CC,A ]) self.assertEqualHexByte(self.cpu.get_cc_value(), 0x89) self.assertEqualHexByte(self.cpu.accu_a.value, 0x89) def test_TFR_Y_B(self): """ transfer 16 bit register in a 8 bit register TODO: verify this behaviour on real hardware! """ self.cpu.index_y.set(0x1234) self.cpu.accu_b.set(0xab) self.cpu_test_run(start=0x4000, end=None, mem=[ 0x1F, 0x29, # TFR Y,B ]) self.assertEqualHexWord(self.cpu.index_y.value, 0x1234) self.assertEqualHexByte(self.cpu.accu_b.value, 0x34) def test_TFR_undefined_A(self): """ transfer undefined register in a 8 bit register TODO: verify this behaviour on real hardware! """ self.cpu.accu_a.set(0x12) self.cpu_test_run(start=0x4000, end=None, mem=[ 0x1F, 0x68, # TFR undefined,A ]) self.assertEqualHexByte(self.cpu.accu_a.value, 0xff)
class Test6809_TFR(BaseCPUTestCase): def test_TFR_A_B(self): pass def test_TFR_B_A(self): pass def test_TFR_X_U(self): ''' LDX #$1234 LDU #$abcd TFR X,U STX $20 STU $30 ''' pass def test_TFR_CC_X(self): ''' transfer 8 bit register in a 16 bit register TODO: verify this behaviour on real hardware! ''' pass def test_TFR_CC_A(self): ''' transfer 8 bit register in a 16 bit register TODO: verify this behaviour on real hardware! ''' pass def test_TFR_Y_B(self): ''' transfer 16 bit register in a 8 bit register TODO: verify this behaviour on real hardware! ''' pass def test_TFR_undefined_A(self): ''' transfer undefined register in a 8 bit register TODO: verify this behaviour on real hardware! ''' pass
8
5
11
0
8
4
1
0.56
1
0
0
0
7
0
7
90
83
6
54
8
46
30
40
8
32
1
4
0
7
1,398
6809/MC6809
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/6809_MC6809/MC6809/components/mc6809_stack.py
MC6809.components.mc6809_stack.StackMixin
class StackMixin: def push_byte(self, stack_pointer, byte): """ pushed a byte onto stack """ # FIXME: self.system_stack_pointer -= 1 stack_pointer.decrement(1) addr = stack_pointer.value # log.info( # log.error( # "%x|\tpush $%x to %s stack at $%x\t|%s", # self.last_op_address, byte, stack_pointer.name, addr, # self.cfg.mem_info.get_shortest(self.last_op_address) # ) self.memory.write_byte(addr, byte) def pull_byte(self, stack_pointer): """ pulled a byte from stack """ addr = stack_pointer.value byte = self.memory.read_byte(addr) # log.info( # log.error( # "%x|\tpull $%x from %s stack at $%x\t|%s", # self.last_op_address, byte, stack_pointer.name, addr, # self.cfg.mem_info.get_shortest(self.last_op_address) # ) # FIXME: self.system_stack_pointer += 1 stack_pointer.increment(1) return byte def push_word(self, stack_pointer, word): # FIXME: self.system_stack_pointer -= 2 stack_pointer.decrement(2) addr = stack_pointer.value # log.info( # log.error( # "%x|\tpush word $%x to %s stack at $%x\t|%s", # self.last_op_address, word, stack_pointer.name, addr, # self.cfg.mem_info.get_shortest(self.last_op_address) # ) self.memory.write_word(addr, word) # hi, lo = divmod(word, 0x100) # self.push_byte(hi) # self.push_byte(lo) def pull_word(self, stack_pointer): addr = stack_pointer.value word = self.memory.read_word(addr) # log.info( # log.error( # "%x|\tpull word $%x from %s stack at $%x\t|%s", # self.last_op_address, word, stack_pointer.name, addr, # self.cfg.mem_info.get_shortest(self.last_op_address) # ) # FIXME: self.system_stack_pointer += 2 stack_pointer.increment(2) return word #### @opcode( # Push A, B, CC, DP, D, X, Y, U, or PC onto stack 0x36, # PSHU (immediate) 0x34, # PSHS (immediate) ) def instruction_PSH(self, opcode, m, register): """ All, some, or none of the processor registers are pushed onto stack (with the exception of stack pointer itself). A single register may be placed on the stack with the condition codes set by doing an autodecrement store onto the stack (example: STX ,--S). source code forms: b7 b6 b5 b4 b3 b2 b1 b0 PC U Y X DP B A CC push order -> CC bits "HNZVC": ----- """ assert register in (self.system_stack_pointer, self.user_stack_pointer) def push(register_str, stack_pointer): register_obj = self.register_str2object[register_str] data = register_obj.value # log.debug("\tpush %s with data $%x", register_obj.name, data) if register_obj.WIDTH == 8: self.push_byte(register, data) else: assert register_obj.WIDTH == 16 self.push_word(register, data) # log.debug("$%x PSH%s post byte: $%x", self.program_counter, register.name, m) # m = postbyte if m & 0x80: push(REG_PC, register) # 16 bit program counter register if m & 0x40: push(REG_U, register) # 16 bit user-stack pointer if m & 0x20: push(REG_Y, register) # 16 bit index register if m & 0x10: push(REG_X, register) # 16 bit index register if m & 0x08: push(REG_DP, register) # 8 bit direct page register if m & 0x04: push(REG_B, register) # 8 bit accumulator if m & 0x02: push(REG_A, register) # 8 bit accumulator if m & 0x01: push(REG_CC, register) # 8 bit condition code register @opcode( # Pull A, B, CC, DP, D, X, Y, U, or PC from stack 0x37, # PULU (immediate) 0x35, # PULS (immediate) ) def instruction_PUL(self, opcode, m, register): """ All, some, or none of the processor registers are pulled from stack (with the exception of stack pointer itself). A single register may be pulled from the stack with condition codes set by doing an autoincrement load from the stack (example: LDX ,S++). source code forms: b7 b6 b5 b4 b3 b2 b1 b0 PC U Y X DP B A CC = pull order CC bits "HNZVC": ccccc """ assert register in (self.system_stack_pointer, self.user_stack_pointer) def pull(register_str, stack_pointer): reg_obj = self.register_str2object[register_str] reg_width = reg_obj.WIDTH # 8 / 16 if reg_width == 8: data = self.pull_byte(stack_pointer) else: assert reg_width == 16 data = self.pull_word(stack_pointer) reg_obj.set(data) # log.debug("$%x PUL%s:", self.program_counter, register.name) # m = postbyte if m & 0x01: pull(REG_CC, register) # 8 bit condition code register if m & 0x02: pull(REG_A, register) # 8 bit accumulator if m & 0x04: pull(REG_B, register) # 8 bit accumulator if m & 0x08: pull(REG_DP, register) # 8 bit direct page register if m & 0x10: pull(REG_X, register) # 16 bit index register if m & 0x20: pull(REG_Y, register) # 16 bit index register if m & 0x40: pull(REG_U, register) # 16 bit user-stack pointer if m & 0x80: pull(REG_PC, register)
class StackMixin: def push_byte(self, stack_pointer, byte): ''' pushed a byte onto stack ''' pass def pull_byte(self, stack_pointer): ''' pulled a byte from stack ''' pass def push_word(self, stack_pointer, word): pass def pull_word(self, stack_pointer): pass @opcode( # Push A, B, CC, DP, D, X, Y, U, or PC onto stack 0x36, # PSHU (immediate) 0x34, # PSHS (immediate) ) def instruction_PSH(self, opcode, m, register): ''' All, some, or none of the processor registers are pushed onto stack (with the exception of stack pointer itself). A single register may be placed on the stack with the condition codes set by doing an autodecrement store onto the stack (example: STX ,--S). source code forms: b7 b6 b5 b4 b3 b2 b1 b0 PC U Y X DP B A CC push order -> CC bits "HNZVC": ----- ''' pass def push_byte(self, stack_pointer, byte): pass @opcode( # Pull A, B, CC, DP, D, X, Y, U, or PC from stack 0x37, # PULU (immediate) 0x35, # PULS (immediate) ) def instruction_PUL(self, opcode, m, register): ''' All, some, or none of the processor registers are pulled from stack (with the exception of stack pointer itself). A single register may be pulled from the stack with condition codes set by doing an autoincrement load from the stack (example: LDX ,S++). source code forms: b7 b6 b5 b4 b3 b2 b1 b0 PC U Y X DP B A CC = pull order CC bits "HNZVC": ccccc ''' pass def pull_byte(self, stack_pointer): pass
11
4
21
3
11
9
3
1
0
0
0
1
6
0
6
6
166
29
80
28
63
80
70
20
61
9
0
1
26
1,399
6809/MC6809
6809_MC6809/MC6809/tests/test_readme.py
MC6809.tests.test_readme.ReadmeTestCase
class ReadmeTestCase(BaseTestCase): def test_main_help(self): stdout = invoke_click(cli, '--help') self.assert_in_content( got=stdout, parts=( 'Usage: ./cli.py [OPTIONS] COMMAND [ARGS]...', ' benchmark ', ' profile ', constants.CLI_EPILOG, ), ) assert_cli_help_in_readme(text_block=stdout, marker='main help') def test_dev_cli_main_help(self): stdout = invoke_click(dev_cli, '--help') self.assert_in_content( got=stdout, parts=( 'Usage: ./dev-cli.py [OPTIONS] COMMAND [ARGS]...', ' check-code-style ', ' coverage ', constants.CLI_EPILOG, ), ) assert_cli_help_in_readme(text_block=stdout, marker='dev help') def test_benchmark_help(self): stdout = invoke_click(cli, 'benchmark', '--help') self.assert_in_content( got=stdout, parts=( 'Usage: ./cli.py benchmark [OPTIONS]', ' --loops ', ' --multiply ', ), ) assert_cli_help_in_readme(text_block=stdout, marker='benchmark help') def test_profile_help(self): stdout = invoke_click(cli, 'profile', '--help') self.assert_in_content( got=stdout, parts=( 'Usage: ./cli.py profile [OPTIONS]', ' --loops ', ' --multiply ', ), ) assert_cli_help_in_readme(text_block=stdout, marker='profile help')
class ReadmeTestCase(BaseTestCase): def test_main_help(self): pass def test_dev_cli_main_help(self): pass def test_benchmark_help(self): pass def test_profile_help(self): pass
5
0
12
0
12
0
1
0
1
0
0
0
4
0
4
4
50
3
47
9
42
0
17
9
12
1
1
0
4